# Using the XOR arithmetic encryption algorithm to share in PHP MySQL application

Source: Internet
Author: User
Tags php mysql
The principle of XOR algorithm

From the main method of encryption, the transposition method is too simple, especially for the case of less data, it is easy to guess the plaintext by ciphertext, and the substitution method is an effective and simple algorithm.

From the characteristics of various substitution methods, the XOR operation is most suitable for simple addition and decryption operations, the principle of this method is: When a number A and another number B is an XOR operation will generate another number C, if the C and B are also the XOR operation, then C will revert to a.

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

(1) The algorithm is simple and can be easily implemented 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 valid for Western characters, the Chinese encryption and decryption can not be restored to the original character.

XOR algorithm implementation

The previous section describes how to encrypt/decrypt using the XOR operation, which will be used to encrypt the user's login information. Based on the principle of the XOR encryption algorithm introduced in the previous section, it is not difficult to write down the following cryptographic decryption functions. The encryption algorithm is listed first.

```<!-Encrypy_xor: Simple encryption function using XOR operation ————————–>
<? php
// Encryption function
functionmyEncrypt (\$ string, \$ key)
{
for (\$ i = 0; \$ i <STRLEN (\$ STRING); p \$ i ++) <>
{
for (\$ j = 0; \$ j <STRLEN (\$ KEY); p \$ j ++) <>
{
\$ string [\$ i] = \$ string [\$ i] ^ \$ key [\$ j];
}
}
return \$ string;
}

```

The 4th line defines the cryptographic function myencrypt (), the input parameter \$string to clear text, and \$key as the key, and the output is ciphertext that uses \$key as the key and uses the 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) iterates over each character of the plaintext with each one of the keys. The principle has been introduced in the previous section and is not restated.
Similarly, similar to cryptographic functions, the following decryption functions can be written.

```// Decryption function
functionmyDecrypt (\$ string, \$ key)
{
for (\$ i = 0; \$ i <STRLEN (\$ STRING); p \$ i ++) <>
{
for (\$ j = 0; \$ j <STRLEN (\$ KEY); p \$ j ++) <>
{
\$ string [\$ i] = \$ key [\$ j] ^ \$ string [\$ i];
}
}
return \$ string;
}
?>

```

Line 4th defines the decryption function mydecrypt (), the input parameter \$string as ciphertext, and \$key as the key, and the output is the plaintext that is generated using \$key as the key and using the XOR decryption algorithm.
Below, a sample application is used to further illustrate the function of cryptographic functions.

```// example
\$ my_key = "1234567890 ″;

```

Line 3rd defines a clear text \$my_password, and then defines the key \$my_key on line 4th.
Lines 5th, 6 call the cryptographic function to generate ciphertext and output, in turn, in the 7th, 8 will decrypt the ciphertext. The result of the
example above is as follows.
implements authentication with the XOR algorithm
The last two sections introduce the principle and implementation of information encryption/decryption using XOR operation, and the following will use this method 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 the user registers, the user needs to add the user password form.
• No one other than the user can obtain their password information, including system designers and database administrators.
• The system can verify the legality of the user based on the password entered by the user.
For this purpose, the XOR algorithm can be used to select the user name as clear text, and the key is a user-defined password, and then the encrypted user name is stored in the database.
In addition, there are two ways to authenticate a legitimate user when a user logs on.
(1) is re-encrypted according to the user name (plaintext) and password (key) information it submits, and uses the encrypted information to compare with the password information stored in the database, if equal, the user is legitimate, otherwise, it is an illegal user.
(2) According to the password information stored in the database (clear text) and user input password (key) information to decrypt, and the encrypted information and user submitted by the user name to compare, if equal, the user is legitimate, otherwise, for illegal users.
Two ways can achieve a 3rd purpose, in this case, will be in the 2nd way. The implementation code for this example can be implemented based on the implementation of 18.4.1 "User Login" and 18.4.2 "Checking user", where the "User login" page does not need to change, and the "Check user" implementation is referenced below.

```<? php
session_start (); // Load the Session library, be sure to put it on the first line
\$ user_name = \$ _ POST ["user_name"];
session_register ("user_name"); // Register \$ user_name variable, note that there is no \$ sign
require_once ("sys_conf.inc"); // System configuration file, including database configuration information
require_once ("encrypy_xor.php"); // Contains xor encryption function files
//Connect to the database
\$ link_id = mysql_connect (\$ DBHOST, \$ DBUSER, \$ DBPWD);
mysql_select_db (\$ DBNAME); // Select the database my_chat
// Check if there is login user information
\$ str = "selectname, passwordfromuserwherename = '\$ user_name'";
\$ result = mysql_query (\$ str, \$ link_id); // Execute query
@ \$ rows = mysql_num_rows (\$ result); // The number of records obtained query results
\$ user_name = \$ _ SESSION ["user_name"];
\$ 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 = 1wherename = '\$ user_name'andpassword =' \$ password_en '";
\$ result = mysql_query (\$ str, \$ link_id); // Execute query
require ("main.php"); // Go to the chat page
}
else
{
}
}
// 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
?>
```

The

7th line introduces the cryptographic function file encrypy_xor.php, which includes the two functions described in the previous section.
Line 19th, use user-submitted user name and password to obtain the encrypted password value, and for the new user, the 44th row of this encrypted value is stored in the database.
In addition, for the old user, in the 24th obtains the user name and the encrypted password information in the database, and uses these two values to decrypt in the 25 line, then checks the user's legitimacy on line 28th by comparing the decrypted value with user-submitted user name information. The section on
Auto-Generate keys
Describes how to encrypt user information using the XOR encryption algorithm, where the password information entered by the user is actually the key in the cryptographic algorithm, and the user name is used as plaintext, although this is a good way to accomplish the function, but logically, This approach seems somewhat unreasonable.
This article describes a technique for automatically generating keys that can be used to encrypt the password that a user submits by using an automatically generated key to make the logic more reasonable.
In this case, assume that the generated key is 512 bits. The code is as follows.

```<! – Keygen.php: Automatically generate keys ————————————>
<? php
// 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); // Generate a random number
\$ k = ((\$ upperbound- \$ lowerbound) +1) * \$ rnd + \$ lowerbound;
\$ strMyKey = \$ strMyKey. \$ k;
}
return \$ strMyKey;
}
// write key to file \$ file_name
functionwrite_key (\$ key, \$ file_name)
{
\$ filename = "C: \ key.txt";
\$ key = generate_key (\$ key, 512);
// Use add mode to open \$ filename, the file pointer will be at the end of the file
if (! \$ handle = fopen (\$ filename, 'w'))
{
print "Cannot open file \$ filename";
exit;
}
// Write \$ key to the file we opened.
if (! fwrite (\$ handle, \$ key))
{
print "Cannot write to file \$ filename";
exit;
}
fclose (\$ handle);
}
// Read the key in the key file
functionget_key (\$ file_name)
{
//open a file
\$ fp = fopen (\$ file_name, "r");
\$ result = "";
while (! feof (\$ fp))
{
\$ buffer = fgets (\$ fp, 4096);
\$ result = \$ result. \$ buffer;
}
return \$ result;
}
/// *
\$ KeyLocation = "C: \ key.txt"; // The file holding the key
\$ key = "123456 ″;
write_key (\$ key, \$ KeyLocation);
echoget_key (\$ KeyLocation);
// * /
?>
```

The code consists of 3 functions.
Generate_key (\$len): Automatically generate a key with a length of \$len
Write_key (\$key, \$file _name): Writes the key to the file \$file_name
Get_key (\$file _name): reads the key value in the key file \$file_name
When used, the first time a user logs on to the system, the key value is automatically generated for it and can be handled in two ways for this key value.
(1) In a field of the database, the disadvantage of this method is that the security of the key in the database can not be guaranteed;
(2) Save this key in the user's local file, so that the key can not be obtained by others, but the disadvantage is that when users use other machines to access the system, you cannot log on.
In this example, the 2nd method is used.
Specifically, line 11th to 18th of the above code generates the key continuously by generating a random number, and increases its complexity through a calculation. The number of lowerbound and Upperbound is actually the ASCII character range you want to use for encryption. The following is an example of a key file that is generated.
208123915925183361116049369344372701567721435181102718332639307390344373445407
524316475863232913993383189547474747394154915312639841226741894189965623523913
011164730113445201935692839710274127251577929493941487145611337531549110895367
593586318332391170941272701152344371709270125776235313540032267139933835677407
617384135696111239130732949469623520815987524358635491542913374933524334454251
400327015367133759324537171709152357391089524342514685239122673135531363151191
833412771743139654 ...
Finally, the key needs to be kept in a secure place on the server, and then the user information can be encrypted/decrypted using a cryptographic algorithm such as XOR. How to use this key in the XOR described in the previous section is very simple and no longer detailed.

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.