By the end of the period, we will take a look at the introduction to information security homework. I happened to encounter the playfair algorithm and the hill algorithm in classical cryptography algorithm. It is interesting to implement it in JavaScript language. I check Baidu while encoding, and then give a good tutorial on the basics of JavaScript.
playfair
Playfair password (English: Playfair cipher or Playfair square) is a replacement password. Written based on a 5*5 square cipher table, with 25 letters arranged in the table. For the 26 letters in English, remove the most commonly used Z to form a password table.
Implementation ideas:
1. Prepare a password list
A key is a word or phrase, and the password table is sorted out based on the key given by the user. If there are duplicate letters, you can remove the duplicate letters afterwards.
For example, the key crazy dog can be compiled into
| C | O | H | M | T |
| R | G | I | N | U |
| A | B | J | P | V |
| Y | E | K | Q | W |
| D | F | L | S | X |
The code copy is as follows:
/*
* Function: compiling password list
*
* Parameters: key (space removal and capitalization processing)
*
* Return: Password table
*/
function createKey(keychars){
//Alphabetical array
var allChars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y'];
//Variable keychars get the position of the letter in the alphabetical table and delete the letter
for(var i = 0 ;i<keychars.length;i++){
var index = allChars.indexOf(keychars[i]);
if (index > -1) {
allChars.splice(index, 1);
}
}
//Insert the letters in the keychar into the alphabet
for(var i = keychars.length-1;i>=0;i--){
allChars.unshift(keychars[i]);
}
//Insert keychars from the first column into the password table
for(var i = 0 ; i<5 ; i++){
for(var j = 0; j<5;j++){
key[j][i] = allChars[i*5+j];
}
}
}
Considering that the duplicate characters and Z need to be removed when inserting keychars into the password table, the design algorithm is as follows:
The code copy is as follows:
/*
* Function: Remove duplicate letters from strings
*
* Parameters: strings that need to be processed
*
* Return: processed string
*/
function removeDuplicate(str){
var result = [],tempStr = "";
var arr = str.split('');//Split the string into an array
//arr.sort();//Sorting
for(var i = 0; i < arr.length; i++){
var repeatBack = true;//The design variable is to ensure that the previous part of the string does not exist in the same characters, because the following algorithm can only ensure that the same characters are connected together
for(var j = 0;j<result.length;j++){
if(arr[i] == result[j])
repeatBack = false;
}
if(arr[i] !== tempStr && repeatBack){
result.push(arr[i]);
tempStr = arr[i];
}else{
continue;
}
}
return result.join("");//Convert array to string
}
2. Organize the clear text
Make a pair of two letters of the plain text. If there are two identical letters next to each other in pairs or the last letter is single, insert a letter X. In the early stage of coding, he was not considerate and refused to enter the number of letters as singular, which made the user experience poor.
var k = document.getElementById("keychars").value.toUpperCase().replace(//s/ig,'');
Remove spaces and convert to uppercase for plain text.
3. Write a cipher text
Plain text encryption rules (from Baidu):
1) If p1 p2 is on the same line, the corresponding ciphertext c1 c2 is the letter close to the right end of p1 p2. The first column is regarded as the right side of the last column. For example, according to the previous table, ct corresponds to oc
2) If p1 p2 is in the same column, the corresponding ciphertext c1 c2 is the letters immediately below p1 p2. The first line is regarded as below the last line.
3) If p1 and p2 are not in the same row and in the same column, then c1 and c2 are letters at the other two corners of the rectangle determined by p1 and p2 (as for horizontal replacement or vertical replacement, you must make an appointment in advance, or try it yourself). As per the previous table, wh corresponds to tk or kt.
For example, according to the above table, the plain text where there is life, there is hope.
You can first organize it into wh er et he re is li fe th er ei sh op ex
Then the ciphertext is: kt yg wo ok gy nl hj of cm yg kg lm mb wf
Turn the ciphertext into capital, and then arrange it in groups of several letters.
For example, in a group of 5, KTYGW OOKGY NLHJO FCMYG KGLMM BWF
4. Decryption
Fill in a 5*5 matrix (repeat the repeated letters and letters z), fill in the remaining positions of the matrix in order in the remaining positions of the matrix, and obtain the plain text from the ciphertext according to the replacement matrix. Do the opposite.
The effect is as shown in the figure:
hill
Hill Password is a replacement password that uses the basic matrix theory principle. Written based on a 5*5 square cipher table, with 25 letters arranged in the table. For the 26 letters in English, remove the most commonly used Z to form a password table.
Implementation ideas:
1. Write an alphabet
var chars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
2. Randomly generate keys
The code copy is as follows:
/*
* Function: Randomly generate keys
*
* Return: Key matrix
*/
function randomCreateKey(){
// Randomly generate numbers from 0 to 26
for(var i = 0;i<3;i++){
for(var j = 0;j<3;j++){
key[i][j] = Math.round(Math.random()*100%26)
}
}
}
3. Key code, process the plain text based on the automatically generated key:
The code copy is as follows:
/*
* Function: hill algorithm
*
* Parameters: uppercase array with multiples of length 3
*
* Return: Encrypted string
*/
function hill(p){
//Uppercase letters cipher text
var res = "";
//Develop the total number of times the string needs to be traversed
var round = Math.round(p.length/3);
//deal with
for(var b = 0;b<round;b++){
//Plain Text 3
var temp3 ="";
var tempArr3 = [];
var sumArr3 = [];
for(var i = 0;i<3;i++){
temp3 += p.shift();
for(var j = 0;j<chars.length;j++){
if(temp3[i] == chars[j])
tempArr3[i] = j;
}
}
//calculate
for(var i =0;i<3;i++){
for(var j = 0;j<3;j++){
sumArr3[i] = (tempArr3[j]*key[i][j])%26;
}
}
//Get the corresponding index of characters in the alphabet
for(var i =0;i<3;i++){
res += chars[sumArr3[i]];
}
}
return res;
};
The effect is as shown in the figure:
The above algorithms have shortcomings:
1. Process-oriented design, high coupling degree
2. Too many nested loops, algorithm efficiency needs to be optimized
3. Inadequate consideration of possible situations, such as not processing when the user enters non-alphabetical characters.
Summarize:
After studying the course Introduction to Information Security for a period of time, I can only understand the basics of information security. Information security is a very interesting subject. When you encounter some problems, think as much as possible, do more, and use more. At the same time, we must also strengthen the accumulation of mathematical foundation, consolidate the JS foundation, and broaden the knowledge. This road has a long way to go.