Home Web Front-end JS Tutorial Javascript implements playfair and hill password algorithms_Basic knowledge

Javascript implements playfair and hill password algorithms_Basic knowledge

May 16, 2016 pm 04:28 PM
javascript

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

Copy code The code is as follows:

/*
* 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          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 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:

Copy code The code 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 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 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

Copy code The code is as follows:

/*
* 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:

Copy code The code is as follows:

/*
* 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 //Plain text 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;
            }
}
                                                                                                                                                            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;
};

The effect is as shown in the figure:

The above algorithm has shortcomings:

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.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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 and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

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

See all articles