Home > Web Front-end > JS Tutorial > body text

Javascript implements playfair and hill password algorithms_Basic knowledge

WBOY
Release: 2016-05-16 16:28:36
Original
1599 people have browsed it

Till the end of the semester, study for homework on the introduction to information security. I happened to come across the playfair algorithm and hill algorithm in classical cryptography algorithms. It was interesting to implement them in JavaScript language. I checked Baidu while coding, and by the way, I learned the basics of JavaScript.

playfair

Playfair cipher (English: Playfair cipher or Playfair square) is a replacement cipher. It is written based on a password table composed of a 5*5 square, with 25 letters arranged in the table. For the 26 letters in English, the most commonly used Z is removed to form a password table.

Implementation ideas:

1. Prepare password table

The key is a word or phrase, and the password table is compiled based on the key given by the user. If there are repeated letters, the subsequent repeated letters can be removed.

If the key is crazy dog, it 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

Copy code The code is as follows:

/*
* Function: Prepare password table
*
* Parameter: Key (after removing spaces and capitalizing)
*
* 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 gets the position of the letter in the alphabetical order table, delete the letter
for(var i = 0 ;i          var index = allChars.indexOf(keychars[i]);
If (index > -1) {
               allChars.splice(index, 1);
}
}
//Insert the letters in keychar into the alphabet
for(var i = keychars.length-1;i>=0;i--){
         allChars.unshift(keychars[i]);
}
//Insert keychars into the password table from the first column
for(var i = 0; i<5; i){
for(var j = 0; j<5 ;j ){
             key[j][i] = allChars[i*5 j];
}
}

Consider the need to remove duplicate characters and Z when inserting keychars into the password table. The design algorithm is as follows:

Copy code The code is as follows:

/*
* Function: Remove repeated letters in a string
*
* Parameter: String that needs to be processed
*
* Return: processed string
*/
function removeDuplicate(str){
var result = [],tempStr = "";
var arr = str.split('');//Split the string into an array
​​​​ //arr.sort();//Sort
for(var i = 0; i < arr.length; i ){
                  var repeatBack = true;//The design variable is to ensure that the same characters do not exist in the front part of the string, because the following algorithm can only ensure that the same characters are connected together
for(var j = 0;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 the array to a string
}

2. Organize plain text

Form a pair of every two letters of the plaintext. If there are two identical letters next to each other in a pair or the last letter is a single letter, insert an X. The initial coding was not thoughtful, and the user forcefully refused to enter an odd number of letters, resulting in a poor user experience.

var k = document.getElementById("keychars").value.toUpperCase().replace(/s/ig,'');
Remove spaces and convert plain text to uppercase.

3. Write ciphertext

Plain text encryption rules (from Baidu):

1) If p1 and p2 are on the same line, the corresponding ciphertext c1 and c2 are the letters immediately to the right of p1 and p2. The first column is considered to be to the right of the last column. For example, according to the previous table, ct corresponds to oc
2) If p1 and p2 are in the same column, the corresponding ciphertext c1 and c2 are the letters immediately below p1 and p2. The first row is considered to be below the last row.
3) If p1 and p2 are not in the same row or column, then c1 and c2 are the letters in 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). According to the previous table, wh corresponds to tk or kt.

For example, according to the above table, the clear text where there is life, there is hope.
It can be organized as 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
Convert the cipher text to uppercase letters and arrange the letters in groups.
For example, a group of 5 is KTYGW OOKGY NLHJO FCMYG KGLMM BWF

4. Decryption
The key is filled in a 5*5 matrix (removing repeated letters and the letter z). Other unused letters in the matrix are filled in the remaining positions of the matrix in order. The plaintext is obtained from the ciphertext according to the replacement matrix. Do the opposite.

The effect is as shown in the figure:

hill

Hill Password is a substitution cipher that uses the principles of basic matrix theory. It is written based on a password table composed of a 5*5 square, with 25 letters arranged in the table. For the 26 letters in English, the most commonly used Z is removed to form a password table.

Implementation ideas:

1, write the 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

Copy code The code is as follows:

/*
* Function: Randomly generate key
*
* 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&)
}
}
}

3. The key code processes the plain text based on the automatically generated key:

Copy code The code is as follows:

/*
* Function: hill algorithm
*
* Parameter: uppercase array whose length is a multiple of 3

* Return: encrypted string
*/
function hill(p){
//Capital letters cipher text
var res = "";
//Determine the total number of times the string needs to be traversed
var round = Math.round(p.length/3);
//Processing
for(var b = 0;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 If(temp3[i] == chars[j])
                   tempArr3[i] = j;
            }
}
                                                                                                                                                            for(var i =0;i<3;i){
for(var j = 0;j<3;j ){
                 sumArr3[i] = (tempArr3[j]*key[i][j])&;
            }
}
//Get the corresponding index of the character 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 algorithm has shortcomings:

1. Process-oriented design, high coupling

2. There are too many nested loops and the algorithm efficiency needs to be optimized

3. Inadequate consideration of possible situations, such as not processing when the user inputs non-alphabetic characters.

Summary:

After studying the course Introduction to Information Security for a while, I can only scratch the surface of information security. Information security is a very interesting subject. When you encounter some problems, you should think about it as much as possible, do it as much as possible, and apply it as much as possible. At the same time, it is also necessary to strengthen the accumulation of mathematical foundation, consolidate the foundation of js, and broaden the knowledge. The road ahead is long and arduous.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!