# Use the XOR algorithm in PHP + MySQL applications

Source: Internet
Author: User
This article introduces an easy-to-use encryption and decryption algorithm: using an exclusive or (XOR) operation. This algorithm is simple in principle and aims to give readers a more intuitive impression on the encryption and decryption of information. The XOR algorithm is too simple in terms of encryption methods, especially when the amount of data is small, it is easy to guess the plaintext by the ciphertext. the replacement method is an effective and simple algorithm. According to the characteristics of various replacement operations, exclusive or operations are most suitable for simple encryption and decryption operations. The principle of this method is: when this article introduces a simple and easy-to-use encryption/decryption algorithm: use an exclusive or (XOR) operation. This algorithm is simple in principle and aims to give readers a more intuitive impression on the encryption/decryption of information.

XOR algorithm principle

From the main method of encryption, the location change method is too simple, especially when the amount of data is small, it is easy to guess the plaintext by the ciphertext, and the replacement method is an effective and simple algorithm.

According to the characteristics of various replacement operations, exclusive or operations are most suitable for simple encryption and decryption operations. The principle of this method is: when one number A and the other number B perform an exclusive or operation, the other number C is generated. if another number C and B are used for an exclusive or operation, C is restored to.

Compared with other simple encryption algorithms, the XOR algorithm has the following advantages.

(1) the algorithm is simple and can be easily implemented in advanced languages.

(2) it is fast and can be used anytime and anywhere.

(3) it is effective for any character. unlike some simple encryption algorithms, it is only valid for Spanish characters and cannot be restored to the original character after Chinese characters are encrypted.

XOR algorithm implementation

The previous section describes how to use the XOR operation to encrypt/decrypt user logon information. According to the principles of the XOR encryption algorithm described in the previous section, it is not difficult to write the following encryption and decryption functions. First, list the encryption algorithms.

1 <! -- Encrypy_xor: the encryption function for simple XOR operations --------------------->
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}

Row 4th defines the encryption function myEncrypt (). the input parameter \$ string is plain text, and \$ key is the key. the output is the ciphertext generated by using \$ key as the key and using XOR encryption algorithm.

6th ~ The outer for loop of 12 rows loops every character of the plaintext string, while the for loop of the inner layer (8th ~ 11 rows) returns an exclusive or operation between each character loop of the plaintext and each bit of the key. The principles are introduced in the previous section and will not be repeated.

Similarly, similar to the encryption function, you can write the following decryption function.

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?>

Row 3 defines the decryption function myDecrypt (). the input parameter \$ string is ciphertext, while \$ key is the key. the output is the plaintext generated by using \$ key as the key and using XOR decryption algorithm.

Next, we will use an application example to further describe the functions of the encryption function.

1 // example
2 \$ my_passWord = "chair ";
4\$ my_key = "1234567890 ";

The first line defines a plaintext \$ my_password, and then defines the key \$ my_key in the second line.

Lines 1 and 6 call the encryption function to generate and output the ciphertext, and in turn decrypt the ciphertext on lines 2 and 8.

The running result of the preceding example is as follows.

Implement identity authentication using XOR algorithms

The previous two sections describe the principles and implementation of information encryption/decryption using XOR operations. Next, we will use this method to encrypt the user's logon password. In this example, the system wants to protect the user's password as follows.

· When a user registers, the user needs to add a user password form.

· No one except the user himself can obtain the password information, including the system designer and database administrator.

· The system can verify the legality of a user based on the password entered by the user.

To achieve the above purpose, you can select the user name as the plaintext when using the XOR algorithm, and the key is the user-defined password, and then the encrypted user name is stored in the database.

In addition, you can use either of the following methods to authenticate a valid user upon logon.

(1) re-encrypt the user name (plaintext) and password (key) information submitted by the user, and compare the encrypted information with the password information stored in the database. if the information is equal, the user is legal. Otherwise, the user is invalid.

(2) decrypt the password information (plaintext) 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 legal. Otherwise, the user is invalid.

Both methods can achieve 3rd goals. In this example, 2nd methods are used. The implementation code in this example can be implemented based on the implementation of "user login" in section 18.4.1 and "check user" in section 18.4.2. the "user login" page does not need to be changed, the implementation of "check users" is as follows.

1 <? Php
2 session_start (); // load the Session Library, which must be placed in the first line
3 \$ user_name = \$ _ POST ["user_name"];
4 session_register ("user_name"); // register the \$ user_name variable. Note that the \$ symbol does not exist.
5
6 require_once ("sys_conf.inc"); // system configuration file, including database configuration information
7 require_once ("encrypy_xor.php"); // contains the xor encryption function file
8
9 // connect to the database
10 \$ link_id = MySQL_connect (\$ DBHOST, \$ DBUSER, \$ DBPWD );
11 mysql_select_db (\$ DBNAME); // select the database my_chat
12
13 // query for logon user information
14 \$ str = "select name, password from user where name = '\$ user_name '";
15 \$ result = mysql_query (\$ str, \$ link_id); // execute the query
16 @ \$ rows = mysql_num_rows (\$ result); // number of records obtained from the query result
17 \$ user_name = \$ _ SESSION ["user_name"];
19 \$ password_en = myEncrypt (\$ user_name, \$ password); // encrypt user information
20
21 // for old users
22 if (\$ rows! = 0)
23 {
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 the query
32 require ("main. php"); // go to the chat page
33}
35 else
36 {
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 the query
45 require ("main. php"); // go to the chat page
46}
47 // Close the database
49?>

The encryption function file encrypy_xor.php is introduced in row 7th, including the two functions described in the previous section.

Row 3 uses the user name and password submitted by the user to obtain the encrypted password value. for new users, the encrypted value of row 3 is stored in the database.

In addition, for old users, 24th obtains the username and encrypted password information in the database, and decrypts the information using these two values in 25 rows, then, the user legality is checked by comparing the decrypted value with the user name information submitted by the user in row 3.

Automatic key generation

The previous section describes how to use the XOR encryption algorithm to encrypt user information. the password entered by the user actually becomes the key in the encryption algorithm, and the user name is used as the plaintext, although this can accomplish the function well, this method seems unreasonable logically.

This article introduces an automatic key generation technology. you can use the automatically generated key to encrypt the plaintext of the password submitted by the user, making the logic more reasonable.

In this example, assume that the generated key is 512 bits. The code is as follows.

1 <! -- Keygen. php: automatically generate the key ------------------------------------>
2 <? Php
3
4 // automatically generate a key with a length of \$ 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); // generates a random number.
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)
22 {
23 \$ filename = "C: \ key.txt ";
24 \$ key = generate_key (\$ key, 512 );
25
26 // open \$ filename in add mode, and the file pointer will be at the end of the file
27 if (! \$ Handle = fopen (\$ filename, 'w '))
28 {
29 PRint "the file \$ filename cannot be opened ";
30 exit;
31}
32
33 // write \$ key to the open file.
34 if (! Fwrite (\$ handle, \$ key ))
35 {
36 print "cannot be written 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 the file
46 \$ fp = fopen (\$ file_name, "r ");
47 \$ result = "";
48 // read data row by row
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 for saving the key
59 \$ key = "123456 ";
60 write_key (\$ key, \$ KeyLocation );
61 echo get_key (\$ KeyLocation );
62 //*/
63?>

The code includes three functions.

· Generate _ key (\$ len): automatically generates a key with a length of \$ len.

· Write _ key (\$ key, \$ file_name): write the key to the file \$ file_name

· Get _ key (\$ file_name): reads the key value in the key file \$ file_name

When a user logs on to the system for the first time, the key value is automatically generated for the user. The key value can be processed in two ways.

(1) store the key into a field in 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 a local file of the user, so that the key can be obtained by others. However, the disadvantage of this method is that when the user uses other machines to access the system, you cannot log on.

In this example, 2nd methods are used.

Specifically, the code above is 11th ~ The 18 rows continuously generate keys by generating random numbers and enhance their complexity through a single calculation. The values of lowerbound and upperbound are actually the ASCII character ranges you want to encrypt. The following is an example of a generated key file.

208123915925183361116049369344372701567721435181102718332639307390344373445407

524316475863232913993383189547474747394154915312639841226741894189965623523913

011164730113445201935692839710274127251577929493941487145611337531549110895367

593586318332391170941272701152344371709270125776235313540032267139933835677407

617384135696111239130732949469623520815987524358635491542913374933524334454251

400327015367133759324537171709152357391089524342514685239122673135531363151191

833412771743139654...

Finally, you need to save the key to a secure place on the server, and then you can use it and other encryption algorithms such as XOR to encrypt/decrypt user information. How to use this key in the XOR introduced in the previous section is very simple and will not be detailed. 2 pages in total. 9 7 1 2

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.