Using XOR computing encryption algorithms in PHPMySQL applications _ PHP Tutorial

Source: Internet
Author: User
Use the XOR algorithm to share data in the PHPMySQL application. The XOR algorithm principle is based on the encryption method. 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. 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.

The code is as follows:



// Encryption function
FunctionmyEncrypt ($ string, $ key)
{
For ($ I = 0; $ I
{
For ($ j = 0; $ j
{
$ String [$ I] = $ string [$ I] ^ $ key [$ j];
}
}
Return $ string;
}


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.

The code is as follows:


// Decryption function
FunctionmyDecrypt ($ string, $ key)
{
For ($ I = 0; $ I
{
For ($ j = 0; $ j
{
$ String [$ I] = $ key [$ j] ^ $ string [$ I];
}
}
Return $ string;
}
?>


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.

The code is as follows:


// Example
$ My_password = "chair ";
Echo "my_password = $ my_password ";
$ My_key = "1234567890 ″;
$ My_password_en = myEncrypt ($ my_password, $ my_key );
Echo "my_password_en = $ my_password_en ";
$ My_password_de = myDecrypt ($ my_password_en, $ my_key );
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 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.
My_password = chair
My_password_en = RYPXC
My_password_de = chair
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" and "check user" in section 18.4.1 and section 18.4.2. the "user login" page does not need to be changed, the implementation of "check users" is as follows.

The code is as follows:


Session_start (); // load the Session database, which must be placed in the first line
$ User_name = $ _ POST ["user_name"];
Session_register ("user_name"); // register the $ user_name variable. Note that the $ symbol does not exist.
Require_once ("sys_conf.inc"); // system configuration file, containing database configuration information
Require_once ("encrypy_xor.php"); // contains the xor encryption function file
// Connect to the database
$ Link_id = mysql_connect ($ DBHOST, $ DBUSER, $ DBPWD );
Mysql_select_db ($ DBNAME); // select the database my_chat
// Query the existence of logon user information
$ Str = "selectname, passwordfromuserwherename = '$ user_name '";
$ Result = mysql_query ($ str, $ link_id); // execute the query
@ $ Rows = mysql_num_rows ($ result); // number of records that obtain the query result
$ User_name = $ _ SESSION ["user_name"];
$ Password = $ _ POST ["password"];
$ Password_en = myEncrypt ($ user_name, $ password); // encrypt user information
// For old users
If ($ rows! = 0)
{
List ($ name, $ pwd) = mysql_fetch_row ($ result );
$ Password_de = myDecrypt ($ pwd, $ password); // decrypt user information
// If the password is entered correctly
If ($ user_name = $ password_de)
{
$ Str = "updateusersetis_online = 1 wherename = '$ user_name' andpassword = '$ password_en '";
$ Result = mysql_query ($ str, $ link_id); // execute the query
Require ("main. php"); // go to the chat page
}
// Incorrect password
Else
{
Require ("relogin. php ");
}
}
// For new users, write their information to the database
Else
{
$ Str = "insertintouser (name, password, is_online) values ('$ user_name', '$ password_en', 1 )";
$ Result = mysql_query ($ str, $ link_id); // execute the query
Require ("main. php"); // go to the chat page
}
// Close the database
Mysql_close ($ link_id );
?>


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.

The code is as follows:



// Automatically generate a key with a length of $ len
Functiongenerate_key ($ len)
{
$ Lowerbound = 35;
$ Upperbound = 96;
$ StrMyKey = "";
For ($ I = 1; $ I <= $ len; $ I ++)
{
$ Rnd = rand (0,100); // generates a random number.
$ K = ($ upperbound-$ lowerbound) + 1) * $ rnd + $ lowerbound;
$ StrMyKey = $ strMyKey. $ k;
}
Return $ strMyKey;
}
// Write the key to the file $ file_name
Functionwrite_key ($ key, $ file_name)
{
$ Filename = "C: \ key.txt ";
$ Key = generate_key ($ key, 512 );
// Open $ filename in add mode, and the file pointer will be at the end of the file
If (! $ Handle = fopen ($ filename, 'w '))
{
Print "the file $ filename cannot be opened ";
Exit;
}
// Write $ key to the open file.
If (! Fwrite ($ handle, $ key ))
{
Print "cannot be written to file $ filename ";
Exit;
}
Fclose ($ handle );
}
// Read the key in the key file
Functionget_key ($ file_name)
{
// Open the file
$ Fp = fopen ($ file_name, "r ");
$ Result = "";
// Read data row by row
While (! Feof ($ fp ))
{
$ Buffer = fgets ($ fp, 4096 );
$ Result = $ result. $ buffer;
}
Return $ result;
}
///*
$ KeyLocation = "C: \ key.txt"; // File for saving the key
$ Key = "123456 ″;
Write_key ($ key, $ KeyLocation );
Echoget_key ($ KeyLocation );
//*/
?>


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.

Token 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...

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.