Home > Article > Backend Development > Use PHP's built-in DES algorithm function to implement data encryption and decryption_PHP tutorial
Due to the needs of the project, it is necessary to write a class that can generate an "authorization code" (the authorization code mainly contains the expiration time of the project). The generated authorization code will be written to a file. Whenever When the project is running, the ciphertext in the file will be automatically read, and then a unique "key" will be used to call a function to decrypt the ciphertext and interpret the expiration time of the project.
Before, I tried to write it myself, mainly base64+md5+reverse string. The algorithm is too simple and can be easily cracked, and it fails to realize the importance of the "key" in encryption and decryption, so it is abandoned.
Later, I searched for relevant information and found that there is a powerful function library built into PHP, namely Mcrypt.
In fact, mcrypt itself provides powerful encryption and decryption methods, and supports many popular public encryption algorithms, such as DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB.
Here is a simple quote from Baidu Encyclopedia’s explanation of “encryption algorithm”:
The basic process of data encryption is to process files or data that were originally plain text according to a certain algorithm, turning it into an unreadable piece of code, usually called "ciphertext", so that it can only be entered when the corresponding password is entered. Only after entering the key can the original content be displayed. In this way, the purpose of protecting the data from being stolen and read by illegal persons is achieved. The reverse of this process is decryption, the process of converting the encoded information into its original data.
Encryption technologies are usually divided into two categories: "symmetric" and "asymmetric".
Symmetric encryption means that encryption and decryption use the same key, usually called "Session Key". This encryption technology is currently widely used. For example, the DES encryption standard adopted by the US government is a typical "symmetric encryption". "Encryption method, its Session Key length is 56Bits.
Asymmetric encryption means that encryption and decryption use different keys. There are usually two keys, called "public key" and "private key". They must be paired together, otherwise the encryption cannot be opened. document. The "public key" here means that it can be disclosed to the outside world, but the "private key" cannot, and can only be known by the holder. Its superiority lies here, because if the symmetric encryption method is transmitting encrypted files on the network, it will be difficult to tell the other party the key, and it may be eavesdropped no matter what method is used. The asymmetric encryption method has two keys, and the "public key" can be made public, so there is no fear of others knowing. The recipient only needs to use his own private key when decrypting, which is very good. This avoids key transmission security issues.
As mentioned earlier, mcrypt supports a variety of internationally public algorithms. In this project, I used the DES algorithm, DES (Data Encryption Standard), which is a symmetric algorithm, fast and suitable for encryption. Large amounts of data.
Next, I will briefly explain several functions used in the encryption class.
1. resource mcrypt_module_open ( string $algorithm , string $algorithm_directory , string $mode , string $mode_directory )
2. int mcrypt_enc_get_iv_size ( resource $td )
3. string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )
This function will create an initialization vector (IV)
Parameters: $source can be MCRYPT_RAND, MCRYPT_DEV_RANDOM, MCRYPT_DEV_URANDOM
Note: PHP5.3.0 or above only supports MCRYPT_RAND
Return value: If successful, a string initial vector will be returned. If failed, False will be returned
4. int mcrypt_enc_get_key_size ( resource $td )
This function can obtain the maximum key length (in bytes) supported by the current algorithm
int mcrypt_generic_init ( resource $td , string $key , string $iv )
Before calling mcrypt_generic() or mdecrypt_generic(), you first need to call this function. This function can help us initialize the buffer to store encrypted data.
Parameter $key: key length. Remember, the current value of $key is smaller than the value returned by the function mcrypt_enc_get_key_size()
Question: Is the larger the value of $key, the better? If there is a classmate association, please help me answer this question.
5. string mcrypt_generic ( resource $td , string $data )
After completing the previous work, you can call this function to encrypt the data.
6. bool mcrypt_generic_deinit ( resource $td )
This function can help us uninstall the currently used encryption module.
返回值:成功时返回 TRUE, 或者在失败时返回 FALSE.
7. string mdecrypt_generic ( resource $td , string $data )
该函数能够用来解密数据。
注意:解密后的数据可能比实际上的更长,可能会有后续的\0,需去掉
8. bool mcrypt_module_close ( resource $td )
关闭指定的加密模块资源句柄
返回值:成功时返回 TRUE, 或者在失败时返回 FALSE.
<?php class authCode { public $ttl;//到期时间 时间格式:20120101(年月日) public $key_1;//密钥1 public $key_2;//密钥2 public $td; public $ks;//密钥的长度 public $iv;//初始向量 public $salt;//盐值(某个特定的字符串) public $encode;//加密后的信息 public $return_array = array(); // 返回带有MAC地址的字串数组 public $mac_addr;//mac地址 public $filepath;//保存密文的文件路径 public function __construct(){ //获取物理地址 $this->mac_addr=$this->getmac(PHP_OS); $this->filepath="./licence.txt"; $this->ttl="20120619";//到期时间 $this->salt="~!@#$";//盐值,用以提高密文的安全性 // echo "<pre class="brush:php;toolbar:false">".print_r(mcrypt_list_algorithms ()).""; // echo "
".print_r(mcrypt_list_modes()).""; } /** * 对明文信息进行加密 * @param $key 密钥 */ public function encode($key) { $this->td = mcrypt_module_open(MCRYPT_DES,'','ecb',''); //使用MCRYPT_DES算法,ecb模式 $size=mcrypt_enc_get_iv_size($this->td);//设置初始向量的大小 $this->iv = mcrypt_create_iv($size, MCRYPT_RAND);//创建初始向量 $this->ks = mcrypt_enc_get_key_size($this->td);//返回所支持的最大的密钥长度(以字节计算) $this->key_1 = substr(md5(md5($key).$this->salt),0,$this->ks); mcrypt_generic_init($this->td, $this->key_1, $this->iv); //初始处理 //要保存到明文 $con=$this->mac_addr.$this->ttl; //加密 $this->encode = mcrypt_generic($this->td, $con); //结束处理 mcrypt_generic_deinit($this->td); //将密文保存到文件中 $this->savetofile(); } /** * 对密文进行解密 * @param $key 密钥 */ public function decode($key) { try { if (!file_exists($this->filepath)){ throw new Exception("授权文件不存在"); }else{//如果授权文件存在的话,则读取授权文件中的密文 $fp=fopen($this->filepath,'r'); $secret=fread($fp,filesize($this->filepath)); $this->key_2 = substr(md5(md5($key).$this->salt),0,$this->ks); //初始解密处理 mcrypt_generic_init($this->td, $this->key_2, $this->iv); //解密 $decrypted = mdecrypt_generic($this->td, $secret); //解密后,可能会有后续的\0,需去掉 $decrypted=trim($decrypted) . "\n"; //结束 mcrypt_generic_deinit($this->td); mcrypt_module_close($this->td); return $decrypted; } }catch (Exception $e){ echo $e->getMessage(); } } /** * 将密文保存到文件中 */ public function savetofile(){ try { $fp=fopen($this->filepath,'w+'); if (!$fp){ throw new Exception("文件操作失败"); } fwrite($fp,$this->encode); fclose($fp); }catch (Exception $e){ echo $e->getMessage(); } } /** * 取得服务器的MAC地址 */ public function getmac($os_type){ switch ( strtolower($os_type) ){ case "linux": $this->forLinux(); break; case "solaris": break; case "unix": break; case "aix": break; default: $this->forWindows(); break; } $temp_array = array(); foreach( $this->return_array as $value ){ if (preg_match("/[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i",$value,$temp_array )){ $mac_addr = $temp_array[0]; break; } } unset($temp_array); return $mac_addr; } /** * windows服务器下执行ipconfig命令 */ public function forWindows(){ @exec("ipconfig /all", $this->return_array); if ( $this->return_array ) return $this->return_array; else{ $ipconfig = $_SERVER["WINDIR"]."\system32\ipconfig.exe"; if ( is_file($ipconfig) ) @exec($ipconfig." /all", $this->return_array); else @exec($_SERVER["WINDIR"]."\system\ipconfig.exe /all", $this->return_array); return $this->return_array; } } /** * Linux服务器下执行ifconfig命令 */ public function forLinux(){ @exec("ifconfig -a", $this->return_array); return $this->return_array; } } $code=new authCode(); //加密 $code->encode("~!@#$%^"); //解密 echo $code->decode("~!@#$%^"); ?>