This article will introduce a simple and easy-to-use encryption/decryption algorithm: using the exclusive OR (XOR) operation. The principle of this algorithm is simple and aims to give readers a more intuitive impression of the encryption/decryption of information.
Principle of XOR algorithm
From the perspective of the main method of encryption, the transposition method is too simple, especially when the amount of data is small, it is easy to guess the plaintext from the ciphertext, and the substitution method is an effective and simple algorithm.
Judging from the characteristics of various substitution operations, the XOR operation is most suitable for simple encryption and decryption operations. The principle of this method is: when a number A and another number B are XORed, another number C will be generated. If Then perform an XOR operation on C and B, and C will be restored to A.
Compared with other simple encryption algorithms, the advantages of the XOR algorithm are as follows.
(1) The algorithm is simple and can be easily implemented in high-level languages.
(2) It is fast and can be used at any time and anywhere.
(3) It is valid for any character. Unlike some simple encryption algorithms, which are only valid for Western characters, Chinese characters cannot be restored to the original characters after encryption and decryption.
XOR algorithm implementation
The previous part introduced the principle of how to use XOR operation for encryption/decryption. This section will use it to encrypt the user's login information. According to the principle of the XOR encryption algorithm introduced in the previous section, it is not difficult to write the following encryption and decryption functions. Encryption algorithms are listed first.
1 <!--encrypy_xor: An encryption function that simply uses XOR operation----------------------->
2 <?php
3 //Encryption function
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 4 defines the encryption function myEncrypt(). The input parameter $string is plaintext, and $key is the key; the output is the ciphertext generated using $key as the key and using the XOR encryption algorithm.
The outer for loop in lines 6 to 12 loops through each character of the plaintext string, while the inner for loop (lines 8 to 11) loops through each character in the plaintext and performs an exception on each bit of the key. OR operation. The principle has been introduced in the previous section and will not be reiterated.
Again, similar to the encryption function, the following decryption function can be written.
1 //decryption function
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?>
Line 4 defines the decryption function myDecrypt (), the input parameter $string is the ciphertext, and $key is the key; the output is the plaintext generated using $key as the key and using the XOR decryption algorithm.
Below, an application example is used to further illustrate the function of the encryption function.
1 //Example
2 $my_password="chair";
3 echo "my_password = $my_password";
4 $my_key="1234567890";
5 $my_password_en=myEncrypt($my_password,$my_key);
6 echo "my_password_en = $my_password_en";
7 $my_password_de=myDecrypt($my_password_en,$my_key);
8 echo "my_password_de = $my_password_de";
Line 3 first defines a clear text $my_password, and then defines the key $my_key on line 4.
Lines 5 and 6 respectively call the encryption function to generate ciphertext and output it; in turn, the ciphertext is decrypted on lines 7 and 8.
The results of running the above example are as follows.
my_password = chair
my_password_en = RYPXC
my_password_de = chair
Implementing identity authentication using XOR algorithm
The previous two parts introduced the principle and implementation of information encryption/decryption using XOR operation. Next, this method will be used to encrypt the user's login password. In this example, in order to protect the user's password, the system wants to achieve the following purposes.
·When registering, the user needs to fill in the user password form.
·In addition to the user himself, no one else can obtain his password information, including system designers and database administrators.
·The system can verify the legitimacy of the user based on the password entered by the user.
In order to achieve the above purpose, when using the XOR algorithm, you can choose the user name as plain text, and the key is a user-defined password, and then store the encrypted user name in the database.
In addition, when a user logs in, there are the following two ways to verify legitimate users.
(1) Re-encrypt based on the user name (plain text) and password (key) information submitted, and use the encrypted information to compare with the password information stored in the database. If they are equal, the user is legal, otherwise, the user is illegal. .
(2) Decrypt based on the password information (plain text) stored in the database and the password (key) information entered by the user, and compare the encrypted information with the user name submitted by the user. If they are equal, the user is legitimate, otherwise, for illegal users.
Both methods can achieve the third purpose. In this example, the second method will be used. The implementation code of this example can be implemented based on the implementation of Section 18.4.1 "User Login" and Section 18.4.2 "Check User". The "User Login" page does not need to be changed. The implementation reference of "Check User" is as follows.
1 <?php
2 session_start(); //Load the Session library, which must be placed on the first line
3 $user_name=$_POST["user_name"];
4 session_register("user_name"); //Register the $user_name variable, note that there is no $ symbol
5
6 require_once("sys_conf.inc"); //System configuration file, including database configuration information
7 require_once("encrypy_xor.php"); //Contains xor encryption function file
8
9 //Connect to the database
10 $link_id=mysql_connect($DBHOST,$DBUSER,$DBPWD);
11 mysql_select_db($DBNAME); //Select database my_chat
12
13 //Query whether there is logged in user information
14 $str="select name,password from user where name ='$user_name'";
15 $result=mysql_query($str,$link_id); //Execute query
16 @$rows=mysql_num_rows($result); //The number of records obtained from the query results
17 $user_name=$_SESSION["user_name"];
18 $password=$_POST["password"];
19 $password_en=myEncrypt($user_name,$password); //Encrypt user information
20
21 //For old users
22 if($rows!=0)
twenty three {
24 list($name,$pwd)=mysql_fetch_row($result);
25 $password_de=myDecrypt($pwd,$password); //Decrypt user information
26
27 //If the password is entered correctly
28 if($user_name==$password_de)
29 {
30 $str="update user set is_online =1 where name ='$user_name' and password='$password_en'";
31 $result=mysql_query($str, $link_id); //Execute query
32 require("main.php"); //Go to the chat page
33}
34 //Password input error
35 else
36 {
37 require("relogin.php");
38 }
39 }
40 //For new users, write their information to the database
41 else
42 {
43 $str="insert into user (name,password,is_online) values('$user_name', '$password_en',1)";
44 $result=mysql_query($str, $link_id); //Execute query
45 require("main.php"); //Go to the chat page
46 }
47 //Close the database
48 mysql_close($link_id);
49 ?>
Line 7 introduces the encryption function file encrypy_xor.php, including the two functions introduced in the previous section.
On line 19, the encrypted password value is obtained using the username and password submitted by the user, and for new users, this encrypted value is stored in the database on line 44.
In addition, for old users, obtain the user name and encrypted password information in the database on line 24, use these two values to decrypt on line 25, and then compare the decrypted value with the user name information submitted by the user on line 28 to check the legitimacy of the user.
The previous part ofautomatically generating keys
introduced how to use the XOR encryption algorithm to encrypt user information. The password information entered by the user actually becomes the key in the encryption algorithm, and the user name is used as plain text. Although this can be very It completes the function well, but logically, this method seems a bit unreasonable.
This article will introduce a technology that automatically generates keys. You can use the automatically generated keys to encrypt the plain text of the password submitted by the user, making the logic more reasonable.
In this example, it is assumed that the generated key is 512 bits. The code is as follows.
1 <!--keygen.php: Automatically generate keys------------------------------------>
2 <?php
3
4 //Automatically generate a key with length $len
5 function generate_key($len)
6 {
7 $lowerbound = 35;
8 $upperbound = 96;
9 $strMyKey = "";
10
11 for($i=1;$i<=$len;$i++)
12 {
13 $rnd=rand(0,100); //Generate random numbers
14 $k = (($upperbound - $lowerbound) + 1) * $rnd + $lowerbound;
15 $strMyKey=$strMyKey.$k;
16}
17 return $strMyKey;
18}
19
20 //Write the key to the file $file_name
21 function write_key($key,$file_name)
twenty two {
23 $filename="C:key.txt";
24 $key=generate_key($key,512);
25
26 //Open $filename using add mode, the file pointer will be at the end of the file
27 if(!$handle=fopen($filename,'w'))
28 {
29 print "Cannot open file $filename";
30 exit;
31}
32
33 //Write $key to the file we opened.
34 if(!fwrite($handle,$key))
35 {
36 print "Cannot write to file $filename";
37 exit;
38 }
39 fclose($handle);
40}
41
42 //Read the key in the key file
43 function get_key($file_name)
44 {
45 //Open file
46 $fp = fopen ($file_name, "r");
47 $result="";
48 //Read line by line
49 while (!feof($fp))
50 {
51 $buffer = fgets($fp, 4096);
52 $result=$result.$buffer;
53}
54 return $result;
55 }
56
57 ///*
58 $KeyLocation = "C:key.txt"; //File to save the key
59 $key="123456";
60 write_key($key,$KeyLocation);
61 echo get_key($KeyLocation);
62 //*/
63 ?>
The code includes 3 functions.
·generate_key($len): automatically generate a key with length $len
·write_key($key,$file_name): write the key to the file $file_name
·get_key($file_name): read the key file $file_name
Whenthe key value
is used, when the user logs in to the system for the first time, the key value is automatically generated for the user. There are two ways to handle this key value.
(1) Store it in a certain field of the database. The disadvantage of this method is that the security of the key in the database cannot be guaranteed;
(2) Save the key in the user's local file, so that This prevents the key from being obtained by others, but the disadvantage of this method is that when users use other machines to access the system, they cannot log in.
In this example, method 2 will be used.
Specifically, lines 11 to 18 of the above code continuously generate keys by generating random numbers, and enhance their complexity through a calculation. The lowerbound and upperbound values are actually the ASCII character range you want to use for encryption. Below is an example of a generated key file.
208123915925183361116049369344372701567721435181102718332639307390344373445407
524316475863232913993383189547474747394154915312639841226741894189965623523913
011164730113445201935692839710274127251577929493941487145611337531549110895367
593586318332391170941272701152344371709270125776235313540032267139933835677407
617384135696111239130732949469623520815987524358635491542913374933524334454251
400327015367133759324537171709152357391089524342514685239122673135531363151191
833412771743139654…
最后,需要把密钥保存在服务器上一个安全的地方,然后就可以利用其和诸如XOR这样的加密算法来对用户信息进行加密/解密了。 How to use this key in the XOR introduced in the previous section is very simple and will not be described in detail. 2 pages in total. 9 7 1 2