Using XOR algorithm to share _php techniques in PHP MySQL applications

Source: Internet
Author: User
Tags decrypt php mysql

XOR algorithm principle

From the main method of encryption, the transposition method is too simple, especially for the small amount of data can be easily guessed by ciphertext, and the replacement method is an effective simple algorithm.

From the characteristics of the operation of various substitution methods, an XOR is best used for simple decryption operations, and the principle is that when a number A and another number B are different or an operation produces another number C, if C and B are again different or operations, C will revert to a.

Compared to other simple encryption algorithms, the advantages of the XOR algorithm are as follows.

(1) The algorithm is simple and easy to implement 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 for western characters valid, the Chinese encryption and then decryption can not revert to the original character.

XOR algorithm implementation

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

Copy Code code as follows:

<!–encrypy_xor: Cryptographic functions that simply use the XOR operation ——————— –>
<?php
Cryptographic functions
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;
}

Line 4th defines the cryptographic function myencrypt (), the input parameter is $string to plaintext, and the $key is the key; the output is a cipher that uses $key as the key and uses an 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) cycles through each character of the plaintext to each of the keys. The principles are described in the previous section and are not restated.
Similarly, similar to cryptographic functions, you can write the following decryption function.
Copy Code code as follows:

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;
}
?>

The 4th line defines the decryption function mydecrypt (), the input parameter is $string, and the $key is the key, and the output is the plaintext generated by using the $key as the key and using the XOR decryption algorithm.
Below, an application example is used to further illustrate the function of the cryptographic function.
Copy Code code 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 first defines a clear text $my_password, and then defines the key $my_key in line 4th.
The 5th and 6 lines call the cryptographic function to generate ciphertext and output respectively, and in turn, the cipher is decrypted in the 7th and 8 rows.
The results of the above example run as follows.
My_password=chair
My_password_en=rypxc
My_password_de=chair
Implementing authentication with an XOR algorithm
The previous two sections describe the principle and implementation of information encryption/decryption using XOR, which is used to encrypt the user's login password. In this case, to protect the user's password, the system wants to achieve the following.
• Users need to add a user password form when they register.
• No one other than the user himself 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.
For these purposes, the XOR algorithm allows you 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, when users log in, there are two ways to authenticate legitimate users.
(1) According to the user name (plaintext) and password (key) information to be encrypted, and use the encrypted information with the database stored in the password information to compare, if equal, then the user is legal, otherwise, for illegal users.
(2) According to the database stored in the password information (plaintext) and user input password (key) information to decrypt, and the encrypted information and user submitted by the user name comparison, if equal, then the user is legitimate, otherwise, for illegal users.
The 3rd goal can be achieved in both ways, in this case, the 2nd way. The implementation code for this example can be implemented on the basis of the 18.4.1 section "User Login" and 18.4.2 "Check user" implementation, where the "User login" page does not need to change, "Check user" Implementation reference is as follows.
Copy Code code as follows:

<?php
Session_Start ()//loading session library, be sure to place 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, including database configuration information
Require_once ("encrypy_xor.php");//contains XOR cryptographic function file
Connecting to a database
$link _id=mysql_connect ($DBHOST, $DBUSER, $DBPWD);
mysql_select_db ($DBNAME);//Select Database My_chat
Query for logon user information
$str = "Selectname,passwordfromuserwherename= ' $user _name '";
$result =mysql_query ($str, $link _id);//Execute Query
@ $rows =mysql_num_rows ($result);//number of record pens 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 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 chat page
}
Close Database
Mysql_close ($link _id);
?>

Line 7th introduces the cryptographic function file encrypy_xor.php, including the two functions described in the previous section.
Line 19th, use the user's submitted username and password to obtain the encrypted password value, and for the new user, the encrypted value is stored in the database in row 44th.
In addition, for the old users, in the 24th to obtain the database in the user name and encrypted password information, and in 25 lines using these two values for decryption, and then in line 28th by comparing the decrypted value and user submitted user name information to check the legality of the user.
Automatically generate keys
The previous section describes how to encrypt user information using the XOR encryption algorithm. The password information entered by the user actually becomes the key in the encryption algorithm, and the user name is used as plaintext, although it is a good way to complete the function, but logically, this method seems somewhat unreasonable.
This article will introduce a technology of automatically generating key, can use the automatically generated key to the user submitted password plaintext encryption, make logic more reasonable.
In this case, assume that the generated key is 512 bits. The code is as follows.
Copy Code code as follows:

<!–keygen.php: Automatically generate key ———————————— >
<?php
Automatically generate a key of length $len
Functiongenerate_key ($len)
{
$lowerbound = 35;
$upperbound = 96;
$strMyKey = "";
for ($i =1; $i <= $len; $i + +)
{
$rnd =rand (0,100);//Generating random numbers
$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);
Open $filename with Add mode, and 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 be written to file $filename";
Exit
}
Fclose ($handle);
}
Read key in key file
Functionget_key ($file _name)
{
Open File
$FP =fopen ($file _name, "R");
$result = "";
Read-by-line
while (!feof ($FP))
{
$buffer =fgets ($fp, 4096);
$result = $result. $buffer;
}
Return$result;
}
///*
$KeyLocation = "C:\key.txt";//Save key file
$key = "123456″;
Write_key ($key, $KeyLocation);
Echoget_key ($KeyLocation);
//*/
?>

The code includes 3 functions.
Generate_key ($len): Automatically generate keys of length $len
Write_key ($key, $file _name): Write key to File $file_name
Get_key ($file _name): Reading key value from $file_name key file
When used, the key value is automatically generated for the user when they log on to the system for the first time, and there are two ways to handle the key value.
(1) Storing it in a field in the database, the disadvantage of which is that the security of the key in the database cannot be guaranteed;
(2) Keep this key in the user's local file, so that the key can be avoided by others, but the disadvantage is that when the user uses other machines to access the system, you cannot log in.
In this case, the 2nd method is used.
Specifically, line 11th to 18th of the above code generates the key continuously by generating random numbers, and increases its complexity by a calculation. The number of lowerbound and Upperbound is actually the range of ASCII characters that you want to encrypt. The following is an example of a key file that is generated.
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 cryptographic algorithms such as XOR to encrypt/decrypt the user's information. How to use this key in the XOR described in the previous section is very simple and no longer detailed.

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.