


Javascript implements playfair and hill password algorithms_Basic knowledge
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
|
/*
* 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
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 for(var j = 0; 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:
/*
* 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 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
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
/*
* Function: Randomly generate key
*
* Return: key matrix
*/
function randomCreateKey(){
// Randomly generate numbers from 0 to 26
for(var i = 0;i for(var j = 0;j key[i][j] = Math.round(Math.random()*100&)
}
}
}
3. The key code processes the plain text based on the automatically generated key:
/*
* 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
var temp3 ="";
var tempArr3 = [];
var sumArr3 = [];
for(var i = 0;i temp3 = p.shift();
for(var j = 0;j
tempArr3[i] = j;
}
}
for(var i =0;i for(var j = 0;j sumArr3[i] = (tempArr3[j]*key[i][j])&;
}
}
//Get the corresponding index of the character in the alphabet
for(var i =0;i res = chars[sumArr3[i]];
}
}
Return res;
};
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.

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools
