This article describes an Easy-to-use encryption/decryption algorithm that uses XOR or XOR operations. This algorithm is simple in principle and aims to make readers have a more intuitive impression on the encryption/decryption of information.
XOR algorithm principle
From the main method of encryption, the transposition method is too simple, especially for the small amount of data can be easily guessed by ciphertext, and the replacement method is an effective simple algorithm.
From the characteristics of the operation of various substitution methods, an XOR is best used for simple decryption operations, and the principle is that when a number A and another number B are different or an operation produces another number C, if C and B are again different or operations, C will revert to a.
Compared to other simple encryption algorithms, the advantages of the XOR algorithm are as follows.
(1) The algorithm is simple and easy to implement for high-level languages.
(2) Fast, can be used at any time, anywhere.
(3) For any character is valid, unlike some simple encryption algorithm, only for western characters valid, the Chinese encryption and then decryption can not revert to the original character.
XOR algorithm implementation
The previous section describes how to encrypt/decrypt using the XOR operation, which is used to encrypt the user's logon information. Based on the principle of the XOR encryption algorithm described in the previous section, it is not difficult to write the following cryptographic decryption function. The encryption algorithm is listed first.
1 <!--encrypy_xor:简单使用XOR运算的加密函数----------------------->
2 <?php
3 //加密函数
4 function myEncrypt($string, $key)
5 {
6 for($i=0; $i<STRLEN($STRING); p $i++)<>
7 {
8 for($j=0; $j<STRLEN($KEY); p $j++)<>
9 {
10 $string[$i] = $string[$i]^$key[$j];
11 }
12 }
13 return $string;
14 }
Line 4th defines the cryptographic function myencrypt (), the input parameter is $string to plaintext, and the $key is the key; the output is a cipher that uses $key as the key and uses an XOR encryption algorithm.
The outer for loop of line 6th to 12th loops through each character of the plaintext string, while the inner for Loop (line 8th to 11th) cycles through each character of the plaintext to each of the keys. The principles are described in the previous section and are not restated.
Similarly, similar to cryptographic functions, you can write the following decryption function.
1 //解密函数
2 function myDecrypt($string, $key)
3 {
4 for($i=0; $i<STRLEN($STRING); p $i++)<>
5 {
6 for($j=0; $j<STRLEN($KEY); p $j++)<>
7 {
8 $string[$i] = $key[$j]^$string[$i];
9 }
10 }
11 return $string;
12 }
13 ?>