


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<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:
/*
* 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
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<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:
/*
* 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<3;i){
temp3 = p.shift();
for(var j = 0;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;
};
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.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
