Javascript implements playfair and hill cryptographic algorithms _ basic knowledge

Source: Internet
Author: User
This article describes how to implement the playfair and hill cryptographic algorithms in javascript. For more information, see the Introduction to information security at the end of the next period. The playfair and hill algorithms in classical cryptographic algorithms are interesting to implement in javascript. You can check Baidu and Code while learning about javascript.

Playfair

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

Implementation ideas:

1. Compile the password table

The 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.

Such as the key crazy dog, programmable

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 is as follows:


/*
* Function: compile a password table.
*
* Parameter: Key (removed spaces and uppercase)
*
* 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'];
// The variable keychars obtains the position of a letter in the alphabetic order table and deletes 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 from the first column to the password table
For (var I = 0; I <5; I ++ ){
For (var j = 0; j <5; j ++ ){
Key [j] [I] = allChars [I * 5 + j];
}
}
}

To insert keychars into the password table, duplicate characters and Z must be removed. The design algorithm is as follows:

The Code is as follows:


/*
* Function: removes duplicate letters from strings.
*
* Parameter: string to be processed
*
* Return: processed string
*/
Function removeDuplicate (str ){
Var result = [], tempStr = "";
Var arr = str. split (''); // splits the string into an array.
// Arr. sort (); // sort
For (var I = 0; I <arr. length; I ++ ){
Var repeatBack = true; // The design variable is used to ensure that the first part of the string does not contain the same character, because the following algorithm can only ensure that the same character is connected.
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 (""); // converts an array to a string.
}

2. Clear Text

Make up one pair of letters for each text. If there are two identical letters next to each other or the last letter is a single pair, insert a letter X. Inefficient at initial encoding, hard-pressed denial of the singular number of letters, poor user experience.

Var k = document. getElementById ("keychars"). value. toUpperCase (). replace (/\ s/ig ,'');
Remove spaces in plaintext and convert them to uppercase.

3. Write the ciphertext

Plaintext encryption rules (from Baidu ):

1) if p1 p2 is in the same row, the corresponding ciphertext c1 c2 is the right Letter 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 a letter close to p1 p2. The first row is considered below the last row.
3) If p1 p2 is not in the same row and is not in the same column, c1 c2 is the other two-angle Letter of the rectangle determined by p1 p2 (as for horizontal replacement or vertical replacement, you must make an appointment in advance, or try it on your own ). For example, in the preceding table, wh corresponds to tk or kt.

For example, according to the above table, the plaintext where there is life, there is hope.
Can be sorted into wh er et he re is li fe th er ei sh op ex
The ciphertext is: kt yg wo OK gy nl hj of cm yg kg lm mb wf.
Converts the ciphertext into uppercase letters, and then arranges several letters in a group.
For example, the five groups are ktygw ookgy nlhjo fcmyg kglmm bwf.

4. decryption
Enter the key in a 5*5 matrix (repeated letters and letters z are extracted). Other unused letters in the matrix are entered in the remaining position of the matrix in order, the plaintext is obtained from the ciphertext based on the replacement matrix. The opposite is true.

Effect

Hill

The Hill Password replaces the Password based on the basic matrix theory. It is written based on a 5*5 square password table, which contains 25 letters. For 26 letters in English, remove the most commonly used Z 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

The Code is as follows:


/*
* Function: generate random keys.
*
* Return value: Key Matrix
*/
Function randomCreateKey (){
// Randomly generate numbers 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: Processes plaintext Based on the automatically generated key:

The Code is as follows:


/*
* Function: hill Algorithm
*
* Parameter: an upper-case array with a length multiple of 3
*
* Return: Encrypted string
*/
Function hill (p ){
// Ciphertext of uppercase letters
Var res = "";
// Specify the total number of times the string is traversed
Var round = Math. round (p. length/3 );
// Process
For (var B = 0; B // Plaintext 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;
}
}
// Computing
For (var I = 0; I <3; I ++ ){
For (var j = 0; j <3; j ++ ){
SumArr3 [I] = (tempArr3 [j] * key [I] [j]) % 26;
}
}
// Obtain the index corresponding to the character in the alphabet
For (var I = 0; I <3; I ++ ){
Res + = chars [sumArr3 [I];
}
}
Return res;
};

Effect

The preceding algorithms are insufficient:

1. process-oriented design with high Coupling

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

3. You may not be considerate about the possible situations. For example, if you do not enter non-letter characters.

Summary:

After studying the introduction to information security for a period of time, I can only understand information security. Information security is a very interesting subject. You can think as much as possible about some problems, learn more, and use more. At the same time, it is necessary to strengthen the accumulation of mathematical basics, consolidate the js basics, and broaden the knowledge. There is a long way to go.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.