PHPMySQL adopts the XOR algorithm in application

Source: Internet
Author: User
Finally, you need to keep the key in 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 apply this key to the XOR in the previous section is very simple and will not be detailed in detail.

This article will first introduce an easy-to-use encryption/decryption algorithm: using an exclusive or (XOR) operation. 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 important 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 features of various exchange operations, exclusive or operations are most suitable for simple encryption and decryption operations. The principle of this method is: when A number A and another number B perform an exclusive or operation, it is born with another number C. If C and B perform an exclusive or operation, C is restored to.

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

(1) the algorithm is simple and easy to implement for advanced languages.

(2) it is fast and can be applied at any time and anywhere.

(3) it is valid 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 a user's logon information. According to the principle of the XOR encryption algorithm first introduced 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 that simply applies the 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}
Row 4th defines the encryption function myEncrypt (). the input parameter $ string is plaintext, and $ key is the key. the output is the ciphertext generated by the application of $ key as the key and the application of 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 principle has been 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?>
The myDecrypt () function is used to define the fourth line. the input parameter $ string is the ciphertext, and $ key is the key. the output is the plaintext generated by the application of $ key as the key and the application of XOR decryption algorithm.

Next, we will use an example to further illustrate the efficacy of the encryption function.

1 // example
2 $ my_password = 'chair ';
3 echo 'My _ password = $ my_password ';
4 $ my_key = '20140901 ';
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 ';

 

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

Lines 5 and 6 tell the encrypted function's natural ciphertext and output it. in turn, the encrypted function is decrypted on lines 5 and 8.

The running results of the preceding example are as follows.

My_password = chair

My_password_en = RYPXC

My_password_de = chair

   Implement identity authentication using XOR algorithms

The previous two sections distinguish the principles and implementation of information encryption/decryption by using XOR operations. Next, we will apply this method to encrypt the user's login password. In this example, the system wants to achieve the following goals to protect the user's password.

· 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 user's legitimacy based on the password entered by the user.

To achieve the above goal, 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, when a user logs on, there are two methods to verify the legitimate user.

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

(2) decrypt the encrypted information based on 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 valid. 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 without the $ symbol
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); // perform the query
16 @ $ rows = mysql_num_rows ($ result); // number of records that obtain 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)
23 {
24 list ($ name, $ pwd) = mysql_fetch_row ($ result );
25 $ password_de = myDecrypt ($ pwd, $ password); // decrypt user information
26
27 // if the password is accurate
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); // perform the 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 into 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); // perform the query
45 require ('main. php'); // go to the chat page
46}
47 // closed Database
48 mysql_close ($ link_id );
49?>


The encryption function file encrypy_xor.php is introduced in row 7th, which contains the two functions first introduced in the previous section.

In row 3, the user name and password submitted by the application user are encrypted and the encrypted value of the new user is stored in the database on Row 3.

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, in row 3, the user's legitimacy is checked by comparing the decrypted value with the username information submitted by the user.

  Active native Key

The previous section first 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 the plaintext, although this can accomplish well, this method seems unfair logically.

This article will first introduce an active Native key technique that can apply the active Native key to encrypt the plaintext of the password submitted by the user, making the logic more fair.

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

1 <! -- Keygen. php: active Native key -------------------------------------->
2 <? Php
3
4 // key with a natural 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 into 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 'file $ filename' cannot be opened ';
30 exit;
31}
32
33 // write $ key into the open file.
34 if (! Fwrite ($ handle, $ key ))
35 {
36 print 'cannot be written into the 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 retaining the key
59 $ key = '000000 ';
60 write_key ($ key, $ KeyLocation );
61 echo get_key ($ KeyLocation );
62 //*/
63?>
The code contains three functions.

· Generate _ key ($ len): The key with a natural length of $ len

· Write _ key ($ key, $ file_name): write the key into 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 in an application, the user takes the initiative to generate the key value for the user. There are two ways to process the key value.

(1) store the key in a field of the database. The problem with this method is that the security of the key in the database cannot be guaranteed;

(2) keep the key in the user's local file, so that the key can be obtained by others. However, the problem with this method is that when the user uses other machines to visit the system, you cannot log on.

In this example, the following 2nd methods are applied.

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

208123915925183361116049369344372701567721435181102718332639307390344373445407

524316475863232913993383189547474747394154915312639841226741894189965623523913

011164730113445201935692839710274127251577929493941487145611337531549110895367

593586318332391170941272701152344371709270125776235313540032267139933835677407

617384135696111239130732949469623520815987524358635491542913374933524334454251

400327015367133759324537171709152357391089524342514685239122673135531363151191

833412771743139654...

Finally, you need to keep the key in 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 apply this key to the XOR in the previous section is very simple and will not be detailed in detail.


 

 

Contact Us

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.