Sharing _php Tutorial with XOR arithmetic encryption algorithm in PHP MySQL application

Source: Internet
Author: User
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.
Copy CodeThe code is as follows:

Cryptographic functions
Functionmyencrypt ($string, $key)
{
for ($i =0; $i
{
for ($j =0; $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.
Copy CodeThe 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;
}
?>

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.
Copy CodeThe 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";

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.
Copy CodeThe code is as follows:
Session_Start ();//loading session library, must be placed in the first line
$user _name=$_post["user_name"];
Session_register ("user_name");//Register $user_name variable, note that there is no $ symbol
Require_once ("Sys_conf.inc");//System configuration file containing database configuration information
Require_once ("encrypy_xor.php");//contains XOR encryption function file
Connecting to a database
$link _id=mysql_connect ($DBHOST, $DBUSER, $DBPWD);
mysql_select_db ($DBNAME);//Select Database My_chat
Querying for the presence of logged-in user information
$str = "Selectname,passwordfromuserwherename= ' $user _name '";
$result =mysql_query ($str, $link _id);//Execute Query
@ $rows =mysql_num_rows ($result);//number of records to get query results
$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=1wherename= ' $user _name ' andpassword= ' $password _en '";
$result =mysql_query ($str, $link _id);//Execute Query
Require ("main.php");//go to the chat page
}
Password input Error
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 Query
Require ("main.php");//go to the chat page
}
Close the database
Mysql_close ($link _id);
?>

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.
Copy CodeThe 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);//Generate random numbers
$k = (($upperbound-$lowerbound) +1) * $rnd + $lowerbound;
$strMyKey = $strMyKey. $k;
}
Return$strmykey;
}
Writes the key to the file $file_name
Functionwrite_key ($key, $file _name)
{
$filename = "C:\key.txt";
$key =generate_key ($key, 512);
Using 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 the $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 File
$FP =fopen ($file _name, "R");
$result = "";
Read row by line
while (!feof ($FP))
{
$buffer =fgets ($fp, 4096);
$result = $result. $buffer;
}
Return$result;
}
///*
$KeyLocation = "C:\key.txt";//The file that holds 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.

http://www.bkjia.com/PHPjc/324110.html www.bkjia.com true http://www.bkjia.com/PHPjc/324110.html techarticle 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 Jane ...

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