Home  >  Article  >  Backend Development  >  Sharing of encryption algorithm using XOR operation in PHP MySQL application

Sharing of encryption algorithm using XOR operation in PHP MySQL application

高洛峰
高洛峰Original
2017-01-07 16:36:081500browse

XOR Algorithm Principle

From the perspective of the main method of encryption, the transposition method is too simple. Especially when the amount of data is small, it is easy to guess the plaintext from the ciphertext, and the substitution method is a good choice. Effective simple algorithm.

From the characteristics of various substitution operations, the XOR operation is most suitable for simple encryption and decryption operations. The principle of this method is: when a number A and another number B are XORed, an XOR operation will be generated. For another number C, if C and B are XORed, C will be restored to A.

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

(1) The algorithm is simple and can be easily implemented in high-level languages.

(2) It is fast and can be used at any time and anywhere.

(3) is valid for any character. Unlike some simple encryption algorithms, which are only valid for Western characters, Chinese characters cannot be restored to the original characters after encryption and decryption.

XOR algorithm implementation

The previous part introduced the principle of how to use XOR operation for encryption/decryption. This section will use it to encrypt the user's login information. According to the principle of the XOR encryption algorithm introduced in the previous section, it is not difficult to write the following encryption and decryption functions. Encryption algorithms are listed first.

<!–encrypy_xor:简单使用XOR运算的加密函数———————–> 
<?php 
//加密函数 
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 4 defines the encryption function myEncrypt(). The input parameter $string is plain text, and $key is the key; the output is the ciphertext generated using $key as the key and using the XOR encryption algorithm.
The outer for loop in lines 6 to 12 loops through each character of the plaintext string, while the inner for loop (lines 8 to 11) loops through each character in the plaintext and each character in the key. Bit XOR operation. The principle has been introduced in the previous section and will not be reiterated.
Similarly, similar to the encryption function, the following decryption function can be written.

//解密函数 
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 4 defines the decryption function myDecrypt(). The input parameter $string is the ciphertext, and $key is the key; the output is the plaintext generated using $key as the key and using the XOR decryption algorithm.
Below, an application example is used to further illustrate the function of the encryption function.

//示例 
$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 3 first defines a plaintext $my_password, and then defines the key $my_key on line 4.
Lines 5 and 6 call the encryption function to generate ciphertext and output it; in turn, the ciphertext is decrypted on lines 7 and 8.
The running results of the above example are as follows.
my_password=chair
my_password_en=RYPXC
my_password_de=chair
Use XOR algorithm to implement authentication
The previous two parts introduce the principle and implementation of information encryption/decryption using XOR operation. The following is , this method will be used 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 registering, the user needs to fill in the user password form.
·In addition to the user himself, no one else can obtain his password information, including system designers and database administrators.
·The system can verify the legitimacy of the user based on the password entered by the user.
In order to achieve the above purpose, when using the XOR algorithm, you can choose the user name as plain text, and the key is a user-defined password, and then store the encrypted user name in the database.
In addition, when a user logs in, there are the following two ways to verify legitimate users.
(1) Re-encrypt based on the submitted user name (plain text) and password (key) information, and use the encrypted information to compare with the password information stored in the database. If they are equal, the user is legitimate, otherwise, For illegal users.
(2) Decrypt the password information (plain text) stored in the database and the password (key) information entered by the user, and compare the encrypted information with the user name submitted by the user. If they are equal, the user is legitimate , otherwise, it is an illegal user.
Both methods can achieve the third purpose. In this example, the second method will be used. The implementation code of this example can be implemented based on the implementation of Section 18.4.1 "User Login" and Section 18.4.2 "Check User". The "User Login" page does not need to be changed. The implementation reference of "Check User" is as follows.

<?php 
session_start();//装载Session库,一定要放在首行 
$user_name=$_POST["user_name"]; 
session_register(“user_name");//注册$user_name变量,注意没有$符号 
require_once(“sys_conf.inc");//系统配置文件,包含数据库配置信息 
require_once(“encrypy_xor.php");//包含xor加密函数文件 
//连接数据库 
$link_id=mysql_connect($DBHOST,$DBUSER,$DBPWD); 
mysql_select_db($DBNAME);//选择数据库my_chat 
//查询是否存在登录用户信息 
$str="selectname,passwordfromuserwherename=&#39;$user_name&#39;"; 
$result=mysql_query($str,$link_id);//执行查询 
@$rows=mysql_num_rows($result);//取得查询结果的记录笔数 
$user_name=$_SESSION["user_name"]; 
$password=$_POST["password"]; 
$password_en=myEncrypt($user_name,$password);//加密用户信息 
//对于老用户 
if($rows!=0) 
{ 
list($name,$pwd)=mysql_fetch_row($result); 
$password_de=myDecrypt($pwd,$password);//解密用户信息 
//如果密码输入正确 
if($user_name==$password_de) 
{ 
$str="updateusersetis_online=1wherename=&#39;$user_name&#39;andpassword=&#39;$password_en&#39;"; 
$result=mysql_query($str,$link_id);//执行查询 
require(“main.php");//转到聊天页面 
} 
//密码输入错误 
else 
{ 
require(“relogin.php"); 
} 
} 
//对于新用户,将其信息写入数据库 
else 
{ 
$str="insertintouser(name,password,is_online)values(‘$user_name&#39;,&#39;$password_en&#39;,1)"; 
$result=mysql_query($str,$link_id);//执行查询 
require(“main.php");//转到聊天页面 
} 
//关闭数据库 
mysql_close($link_id); 
?>

Line 7 introduces the encryption function file encrypy_xor.php, including the two functions introduced in the previous section.
In line 19, the user name and password submitted by the user are used to obtain the encrypted password value, and for new users, the encrypted value is stored in the database in line 44.
In addition, for old users, obtain the user name and encrypted password information in the database on line 24, and use these two values ​​​​to decrypt on line 25, and then compare the decrypted value with the user submitted on line 28 Username information to check the legitimacy of the user.
Automatically generate keys
The previous part introduced how to use the XOR encryption algorithm to encrypt user information. Among them, the password information entered by the user actually becomes the key in the encryption algorithm, and the user name is used as plain text Using , while this does the job well, logically this approach seems a bit unsound.
This article will introduce a technology that automatically generates keys. You can use the automatically generated keys to encrypt the plain text of the password submitted by the user, making the logic more reasonable.
In this example, it is assumed that the generated key is 512 bits. code show as below.

<!–keygen.php:自动生成密钥————————————> 
<?php 
//自动生成长度为$len的密钥 
functiongenerate_key($len) 
{ 
$lowerbound=35; 
$upperbound=96; 
$strMyKey=""; 
for($i=1;$i<=$len;$i++) 
{ 
$rnd=rand(0,100);//产生随机数 
$k=(($upperbound-$lowerbound)+1)*$rnd+$lowerbound; 
$strMyKey=$strMyKey.$k; 
} 
return$strMyKey; 
} 
//将密钥写入文件$file_name 
functionwrite_key($key,$file_name) 
{ 
$filename="C:\key.txt"; 
$key=generate_key($key,512); 
//使用添加模式打开$filename,文件指针将会在文件的末尾 
if(!$handle=fopen($filename,&#39;w&#39;)) 
{ 
print"不能打开文件$filename"; 
exit; 
} 
//将$key写入到我们打开的文件中。 
if(!fwrite($handle,$key)) 
{ 
print"不能写入到文件$filename"; 
exit; 
} 
fclose($handle); 
} 
//读取密钥文件中的密钥 
functionget_key($file_name) 
{ 
//打开文件 
$fp=fopen($file_name,"r"); 
$result=""; 
//逐行读取 
while(!feof($fp)) 
{ 
$buffer=fgets($fp,4096); 
$result=$result.$buffer; 
} 
return$result; 
} 
///* 
$KeyLocation="C:\key.txt";//保存密钥的文件 
$key="123456″; 
write_key($key,$KeyLocation); 
echoget_key($KeyLocation); 
//*/ 
?>

代码包括3个函数。 
◆ generate_key($len):自动生成长度为$len的密钥 
◆ write_key($key,$file_name):将密钥写入文件$file_name 
◆ get_key($file_name):读取密钥文件$file_name中的密钥值 
在使用时,当用户第一次登录系统时,自动为其生成密钥值,对于这个密钥值,可以有两种方式来处理。 
(1)将其存入数据库的某个字段中,这种方法的缺点是密钥在数据库中的安全性无法得到保证; 
(2)将这个密钥保存在用户本地的文件中,这样就可以避免密钥被别人获取,但这种方式的缺点是,当用户使用其他机器访问系统时,就无法登录。 
本例中,将使用第2种方式。 
具体地,上面代码第11~18行通过生成随机数的方式来不断生成密钥,并通过一个计算来增强其复杂性。其中的lowerbound和upperbound的数值其实就是你想使用来加密的ASCII字符范围。下面是生成的一个密钥文件示例。 
208123915925183361116049369344372701567721435181102718332639307390344373445407 
524316475863232913993383189547474747394154915312639841226741894189965623523913 
011164730113445201935692839710274127251577929493941487145611337531549110895367 
593586318332391170941272701152344371709270125776235313540032267139933835677407 
617384135696111239130732949469623520815987524358635491542913374933524334454251 
400327015367133759324537171709152357391089524342514685239122673135531363151191 
833412771743139654… 
最后,需要把密钥保存在服务器上一个安全的地方,然后就可以利用其和诸如XOR这样的加密算法来对用户信息进行加密/解密了。如何在上一部分介绍的XOR中使用这个密钥非常简单,不再详述。


更多PHP MySQL应用中使用XOR运算加密算法分享相关文章请关注PHP中文网!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn