Using XOR arithmetic encryption algorithm in PHP+MYSQL application

Source: Internet
Author: User
Keywords Using XOR arithmetic encryption algorithm in PHP+MYSQL application
Tags decrypt

This article describes an easy-to-use encryption/decryption algorithm that uses XOR (XOR) operations. This algorithm is simple in principle and is designed to make readers have a more intuitive impression on the encryption/decryption of information.

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.

1!--encrypy_xor: Simple cryptographic function with XOR operation----------------------->
2 3//Cryptographic functions
4 function Myencrypt ($string, $key)
5 {
6 for ($i =0; $i 7 {
8 for ($j =0; $j 9 {
$string [$i] = $string [$i]^ $key [$j];
11}
12}
return $string;
14}

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.

1//Decryption function
2 function Mydecrypt ($string, $key)
3 {
4 for ($i =0; $i 5 {
6 for ($j =0; $j 7 {
8 $string [$i] = $key [$j]^ $string [$i];
9}
10}
return $string;
12}
13? >

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.

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 3rd defines a plaintext $my_password, and then defines the key $my_key on line 4th.

5th, 6 lines call the encryption function to generate ciphertext and output, in turn, in the 7th, 8 will decrypt the ciphertext.

The results of the above example run as follows.

My_password = Chair

My_password_en = RYPXC

My_password_de = Chair

Using the XOR algorithm for authentication

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 according to the password entered by the user.

To achieve this, the XOR algorithm can be used to select the user name as plaintext, 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 in.

(1) The user name (clear text) and password (key) information is re-encrypted according to its submission, and the encrypted information is used to compare with the password information stored in the database, if it is 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.

The 3rd goal can be achieved in both ways, and in this case, the 2nd approach will be used. 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.

1 <?php
2 session_start (); Load session library, must be placed in the first row
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 files, including database configuration information
7 require_once ("encrypy_xor.php"); Contains an XOR cryptographic function file
8
9//Connect to Database
$link _id=mysql_connect ($DBHOST, $DBUSER, $DBPWD);
mysql_select_db ($DBNAME); Select Database My_chat
12
13//Query for login user information
$str = "Select Name,password from user where name = ' $user _name '";
$result =mysql_query ($str, $link _id); Execute Query
@ $rows =mysql_num_rows ($result); Number of records to get the results of the query
$user _name=$_session["user_name"];
$password =$_post["Password"];
$password _en=myencrypt ($user _name, $password); Encrypt user Information
20
21//For old users
if ($rows!=0)
23 {
List ($name, $pwd) =mysql_fetch_row ($result);
$password _de=mydecrypt ($pwd, $password); Decrypting user Information
26
27//If password is entered correctly
if ($user _name== $password _de)
29 {
$STR = "Update user set Is_online =1 where name = ' $user _name ' and password= ' $password _en '";
$result =mysql_query ($str, $link _id); Execute Query
Require ("main.php"); Go to the chat page
33}
34//Password input error
+ Else
36 {
Panax Notoginseng require ("relogin.php");
38}
39}
40//For new users, write their information to the database
$ else
42 {
$str = "INSERT into user (Name,password,is_online) VALUES (' $user _name ', ' $password _en ', 1)";
$result =mysql_query ($str, $link _id); Execute Query
Require ("main.php"); Go to the chat page
46}
47//Close Database
Mysql_close ($link _id);
49? >

Line 7th 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 in 25 lines uses these two values to decrypt, and then on the 28th line checks the user's legitimacy by comparing the decrypted value with the user's user name information.

Automatically generate keys

The previous section describes how to use the XOR encryption algorithm to encrypt the user information, in which the password information entered by the user is actually the key in the encryption algorithm, and the user name is used as plaintext, although this can do a good job, but logically, this method seems unreasonable.

This article introduces a technique for automatically generating keys, which can be used to encrypt the password that the user submits by using an automatically generated key, making the logic more reasonable.

This example assumes that the generated key is 512 bits. The code is as follows.

1!--keygen.php: Automatically generate 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
One for ($i =1; $i <= $len; $i + +)
12 {
$rnd =rand (0,100); Generate random numbers
$k = (($upperbound-$lowerbound) + 1) * $rnd + $lowerbound;
$strMyKey = $strMyKey. $k;
16}
$strMyKey;
18}
19
20//write key to file $file_name
function Write_key ($key, $file _name)
22 {
$filename = "C:\key.txt";
$key =generate_key ($key, 512);
25
26//Use Add mode to open $filename, the file pointer will be at the end of the file
if (! $handle =fopen ($filename, ' W '))
28 {
PRint "Cannot open file $filename";
Exit;
31}
32
33//Writes $key to our open file.
if (!fwrite ($handle, $key))
35 {
Print "Cannot write to file $filename";
PNS exit;
38}
Fclose ($handle);
40}
41
42//Read the key in the key file
Get_key function ($file _name)
44 {
45//Open File
$fp = fopen ($file _name, "R");
$result = "";
48//Progressive Read
(!feof ($FP))
50 {
Wuyi $buffer = fgets ($fp, 4096);
$result = $result. $buffer;
53}
The return $result;
55}
56
57///*
$KeyLocation = "C:\key.txt"; The file where the key is saved
$key = "123456";
Write_key ($key, $KeyLocation);
echo Get_key ($KeyLocation);
62//*/
63? >

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. A total of 2 pages. 9 7 1 2

  • Related Article

    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.