JavaScript implements Playfair and Hill cipher Algorithms _ Basics

Source: Internet
Author: User
Tags array to string alphanumeric characters

At the end of the semester, tutorial information security Introduction homework. Just encounter the classical cryptography algorithm Playfair algorithm and hill algorithm, using JavaScript language to achieve is in the fun, while Baidu Edge code, by the way a good tutorial on JavaScript basics.

Playfair

Playfair Password (English: Playfair cipher or Playfair Square) is a replacement password. Based on a 5*5-square cipher table, the table is lined with 25 letters. For the 26 letters in English, remove the most commonly used Z, form the password table.

Realize the idea:

1. Code List

The key is a word or phrase, and the password table is sorted out according to the key given by the user. If you have duplicate letters, you can remove the repeated letters from behind.

such as 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

Copy Code code as follows:

/*
* Function: Code list
*
* Parameters: Key (after removing whitespace and uppercase processing)
*
* Return: Password table
*/
function CreateKey (keychars) {
Array of alphabetical order
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 letter in alphabetical order table position, 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 Letters from 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];
}
}
}

When considering inserting keychars into the password table, you need to remove duplicate characters and z, and the design algorithm is as follows:

Copy Code code as follows:

/*
* Function: Remove duplicate letters from string
*
* Parameter: string to be processed
*
* Return: Processed string
*/
function Removeduplicate (str) {
var result = [],TEMPSTR = "";
var arr = str.split (');//split string into groups
Arr.sort ()//Sort
for (var i = 0; i < arr.length; i++) {
var repeatback = true;//Design variable is to ensure that the same characters do not exist in the previous part of the string, because the following algorithm only ensures 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, sorting out the clear text

Make a pair of clear text every two letters. If there are two identical letters after the pair or the last letter is single, insert a letter x. The initial coding was poorly considered, and the hard way to refuse to enter the number of letters is singular, the user experience is poor.

var k = document.getElementById ("Keychars"). Value.touppercase (). Replace (/\s/ig, ' ");
Remove whitespace from plaintext and convert to uppercase processing.

3, write ciphertext

PlainText encryption rules (from Baidu):

1 if the P1 P2 on the same line, the corresponding ciphertext C1 C2 is close to the P1 P2 the right side of the letter. The first column is seen as the right side of the last column. For example, according to the preceding table, CT corresponds to OC
2 if the P1 P2 in the same column, the corresponding ciphertext C1 C2 is the letter immediately below the P1 P2. The first line is considered to be below the last line.
3 If the P1 P2 is not in the same row and is not in the same column, then C1 C2 is the other two-corner letter of the rectangle determined by P1 P2 (for either horizontal or vertical substitution, either in advance or on its own). As in the previous table, WH corresponds to TK or kt.

For example, in accordance with the previous table, the plaintext where there is life,there is hope.
Can first be sorted into WH er et he re are li fe th er ei sh op ex
Then the cipher is: kt yg wo ok gy nl hj of cm YG kg lm MB WF
Turn the redaction into uppercase, and then arrange the letters in a group.
such as a group of 5 is KTYGW ookgy nlhjo fcmyg kglmm BWF

4, decryption
Fill in a 5*5 matrix (out of duplicate letters and letters Z), the other unused letters in the matrix are filled in the rest of the matrix in order, according to the replacement matrix from the cipher text. In the opposite way.

Implementation of the effect as shown in figure:

Hill

Hill code (Hill Password) is the use of basic matrix theory to replace the password. Based on a 5*5-square cipher table, the table is lined with 25 letters. For the 26 letters in English, remove the most commonly used Z, form the password table.

Realize the idea:

1, writing 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 generated key

Copy Code code as follows:

/*
* Function: Randomly generate key
*
* Return: Key matrix
*/
function Randomcreatekey () {
Randomly generated 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, the key code, according to the automatically generated key, the clear text processing:

Copy Code code as follows:

/*
* Function: Hill algorithm
*
* Parameter: An uppercase array of multiples of 3 in length
*
* Return: Encrypted string
*/
Function Hill (p) {
Upper-Case Cipher text
var res = "";
Make a total number of times that you need to traverse a string
var round = Math.Round (P.LENGTH/3);
Processing
for (var B = 0;b<round;b++) {
PlainText 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;
}
}
Calculation
for (var i =0;i<3;i++) {
for (var j = 0;j<3;j++) {
Sumarr3[i] = (temparr3[j]*key[i][j])%26;
}
}
Gets the character's corresponding index in the alphabet
for (var i =0;i<3;i++) {
res = + Chars[sumarr3[i]];
}
}
return res;
};

Implementation of the effect as shown in figure:

The above algorithms are insufficient:

1, process-oriented design, high coupling degree

2, too many nested loops, algorithm efficiency needs to be optimized

3, consider a situation that may occur, for example, when the user does not enter Non-alphanumeric characters to be processed.

Summarize:

Learn a period of information security Introduction This course, can only know the fur of information security. Information security is a very interesting subject, usually encountered some problems as much as possible thinking, more hands-on, more use. At the same time also to strengthen the accumulation of mathematical foundation, to consolidate the JS Foundation, broaden knowledge. This road is a long way off.

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.