JavaScript implements Playfair and Hill cipher algorithms

Source: Internet
Author: User

At the end of the semester, tutorial information security Introduction operations. The Playfair algorithm in the Classical cryptography algorithm and hill algorithm, in JavaScript language to realize it is interesting, while looking for Baidu side code, by the way a good tutorial JavaScript base.

Playfair

Playfair Password (English: Playfair cipher or Playfair Square) is a replacement password. written according to a cipher table of a 5*5 square, with 25 letters arranged in a table. For the English 26 letters, remove the most commonly used Z, form the cipher table.

Implementation ideas:

1, compiling the password list

  A key is a word or phrase, and the password table is organized according to the key given by the user. If you have duplicate letters, you can remove the repeated letters from the back. 

if 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

 

/** Function: Compile password table * * Parameters: Key (after removing space and uppercase processing) * * Return: Password table*/functionCreateKey (keychars) {//Alphabetical Array    varAllchars = [' 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 table, deleting the letter     for(vari = 0; i<keychars.length;i++){        varindex =Allchars.indexof (Keychars[i]); if(Index >-1) {allchars.splice (index,1); }    }       //Insert Letters from Keychar into the alphabet     for(vari = keychars.length-1;i>=0;i--) {allchars.unshift (keychars[i]); }        //inserting keychars into the password table from the first column     for(vari = 0; i<5; i++){         for(varj = 0; J<5; j + +) {Key[j][i]= allchars[i*5+J]; }    }}    

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

/** Function: Remove repeating letter in String * * parameter: string to be processed * * return: Processed string*/functionremoveduplicate (str) {varresult = [],TEMPSTR = ""; vararr = Str.split (");//split a string into an array        //Arr.sort ();//Sort         for(vari = 0; i < arr.length; i++){            varRepeatback =true;//The design variable is to ensure that the first part of the string does not have the same character, because the following algorithm only ensures that the same characters are joined together             for(varj = 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; }        }        returnResult.join ("");//convert an array to a string}

2, clean up the clear text

  Make a pair of clear text every two letters. If the pair has two identical letters close to each other or the last letter is single, insert a letter x. Early coding is poorly considered, hard to reject the number of letters in the singular, the user experience is poor.

var k = document.getElementById ("Keychars"). Value.touppercase (). Replace (/\s/ig, ');

White space is removed from the plaintext and converted to uppercase.

3, Writing ciphertext

plaintext encryption rules (from Baidu):1) If P1 P2 is on the same line, the corresponding cipher C1 C2 is the letter that is close to the right end of P1 P2 respectively. The first column is considered to be the right of the last column. For example, according to the preceding table, the CT corresponds to OC2) If P1 P2 is in the same column, the corresponding ciphertext C1 C2 are the letters immediately below the P1 P2 respectively. 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, the C1 C2 is the other two-corner letter of the rectangle determined by P1 P2 (as for horizontal or vertical substitution, or if you want to do it yourself). If you follow the preceding table, WH corresponds to TK or kt. for example, in accordance with the above table, clear text where there is Life,there is hope.can be sorted first for WH er et he re is li fe th er ei sh op exthen ciphertext: kt yg wo ok gy nl hj of cm YG kg lm MB WFturn redaction into uppercase, then arrange them in groups of letters. such as 5 a group is KTYGW ookgy nlhjo fcmyg kglmm BWF4, decryptionFill in the key in a 5*5 matrix (go out duplicate letters and letters Z), the other unused letters in the matrix are filled in order in the matrix remaining position, according to the substitution matrix by the ciphertext to get clear text. The opposite way. Achieve Results

Hill

Hill code (Hill Password) is a replacement password using basic matrix theory. Written according to a cipher table of a 5*5 square, with 25 letters arranged in a table. For the English 26 letters, remove the most commonly used Z, form the cipher 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 generated keys

/* *    function: Randomly generated 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++) {              = Math.Round (Math.random () *100%26)     }}}

3, the key code, according to the auto-generated key, the clear text processing:

/** Function: Hill algorithm * * parameter: Length is a multiple of 3 uppercase array * * return: Encrypted string*/functionHill (p) {//Uppercase Ciphertext    varres = ""; //set the number of times the string will be traversed by the line in total    varRound = Math.Round (P.LENGTH/3);//processing     for(varb = 0;b<round;b++){        //Clear Text 3            varTemp3 = ""; varTEMPARR3 = []; varSUMARR3 = [];  for(vari = 0;i<3;i++) {Temp3+=P.shift ();  for(varj = 0;j<chars.length;j++){                if(Temp3[i] = =Chars[j]) temparr3[i]=J; }        }                //Calculation         for(varI =0;i<3;i++){             for(varj = 0;j<3;j++) {Sumarr3[i]= (Temparr3[j]*key[i][j])%26; }        }                //get characters in the alphabet corresponding to the index         for(varI =0;i<3;i++) {res+=Chars[sumarr3[i]]; }    }    returnRes;}; 

Achieve results

The above algorithm has insufficient:

1, process-oriented design, high coupling degree

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

3, it is not considered possible to consider the situation, for example, do not enter the user non-alphabetic characters when processing.

Summarize:

Learn a period of time information security Introduction This course, only for information security to understand fur. Information security is a very interesting subject, usually encountered some problems as much as possible to think, more hands-on, more use. At the same time, we should strengthen the accumulation of mathematical Foundation, Consolidate JS Foundation, broaden knowledge. The road is a heavy one.

JavaScript implements Playfair and Hill cipher algorithms

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.