PHP+MYSQL application encryption algorithm using XOR operation

Source: Internet
Author: User
Tags exit decrypt log mysql query require strlen valid
This article describes an Easy-to-use encryption/decryption algorithm that uses XOR or XOR operations. This algorithm is simple in principle and aims to make readers have a more intuitive impression on the encryption/decryption of information.

   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.

1!--encrypy_xor: Cryptographic functions that simply use the XOR operation-----------------------
2 <?php
3//Encryption function
4 function Myencrypt ($string, $key)
5 {
6 for ($i =0; $i <strlen ($STRING); p $i + +) <>
7 {
8 for ($j =0; $j <strlen ($KEY); p $j + +) <>
9 {
$string [$i] = $string [$i]^ $key [$j];
11}
12}
return $string;
14}
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.

1//Decryption function
2 function Mydecrypt ($string, $key)
3 {
4 for ($i =0; $i <strlen ($STRING); p $i + +) <>
5 {
6 for ($j =0; $j <strlen ($KEY); p $j + +) <>
7 {
8 $string [$i] = $key [$j]^ $string [$i];
9}
10}
One return $string;
12}
13? >
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.

1//Sample
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 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.

1 <?php
2 session_start (); Load the session library, be sure to put it in the first line
3 $user _name=$_post["user_name"];
4 Session_register ("user_name"); Register $user_name variable, note 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//Connection Database
$link _id=mysql_connect ($DBHOST, $DBUSER, $DBPWD);
One 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 record pens to get query results
$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); Decrypt User Information
26
27//If the 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 chat page
33}
34//Password input error
Or else
36 {
Panax Notoginseng require ("relogin.php");
38}
39}
40//For new users, write their information to the database
Or 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 chat page
46}
47//Close the database
Mysql_close ($link _id);
49? >


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.

1!--keygen.php: Automatically generate key------------------------------------
2 <?php
3
4//Automatically generate a $len length of the key
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}
return $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//write $key to our open file.
if (!fwrite ($handle, $key))
35 {
Print "cannot be written to file $filename";
Panax Notoginseng exit;
38}
Fclose ($handle);
40}
41
42//Read the key in the key file
_name function Get_key ($file)
44 {
45//Open File
$fp = fopen ($file _name, "R");
$result = "";
48//Line-by-row reading
while (!feof ($FP))
50 {
Wuyi $buffer = fgets ($fp, 4096);
$result = $result. $buffer;
53}
The return $result;
55}
56
57///*
$KeyLocation = "C:\key.txt"; The file that holds the key
$key = "123456";
Write_key ($key, $KeyLocation);
echo Get_key ($KeyLocation);
62//*/
63? >
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.

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.