Home >Backend Development >PHP Tutorial >Encrypt and decrypt data through DES algorithm through PHP's built-in functions

Encrypt and decrypt data through DES algorithm through PHP's built-in functions

高洛峰
高洛峰Original
2016-12-21 09:49:191059browse

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 the project is run, It will automatically read the ciphertext in the file, and then use the unique "key" to call a function to decrypt the ciphertext and interpret the expiration time of the project.
Before, I tried to write it first, 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 to make it an unreadable piece of code, usually called "Cryptotext" allows the original content to be displayed only after entering the corresponding key. 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 technology is usually divided into two categories: "symmetric" and "asymmetric".
 Symmetric encryption uses the same key for encryption and decryption, often called "Session Key." This encryption technology is currently widely used. For example, the DES encryption standard adopted by the U.S. government is a typical "symmetric" 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 encrypted file cannot be opened. 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 encrypting large amounts of data. occasion.
Next, I will briefly explain several functions used in the encryption class.

------------------------------------------------ --------------------------------
resource mcrypt_module_open ( string $algorithm , string $algorithm_directory , string $mode , string $ mode_directory )
Parameter $algorithm: The algorithm to be used, you can view all supported algorithm names through the function mcrypt_list_algorithms()
Parameter $mode: Which mode to use, similarly, you can use the built-in function mcrypt_list_algorithms() to view all supported modes

------------------------------------------------ --------------------------------
int mcrypt_enc_get_iv_size ( resource $td )
This function will return the initialization of the algorithm used The size of the vector (IV) (seems a bit abstract), returns 0 if IV is ignored in the algorithm.
The parameter $td is the return value of the mcrypt_module_open function.

------------------------------------------------ --------------------------------
string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )
This The 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 will be returned Initial vector, if failure occurs, False will be returned

---------------------------------------- ----------------------------------------
int mcrypt_enc_get_key_size ( resource $td )
This The 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()
问题:$key的值,越大越好吗?有同学会的,帮忙解答下。 

-------------------------------------------------------------------------------- 
string mcrypt_generic ( resource $td , string $data ) 
完成了前面的工作之后,就可以调用该函数用以加密数据了。 
参数$data:要加密的数据内容 
返回值:返回加密后的密文 

-------------------------------------------------------------------------------- 
bool mcrypt_generic_deinit ( resource $td ) 
该函数能够帮我们卸载当前使用的加密模块。 
返回值 
成功时返回 TRUE, 或者在失败时返回 FALSE. 

-------------------------------------------------------------------------------- 
string mdecrypt_generic ( resource $td , string $data ) 
该函数能够用来解密数据。 
注意:解密后的数据可能比实际上的更长,可能会有后续的\0,需去掉 

-------------------------------------------------------------------------------- 
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("~!@#$%^"); ?>

更多通过PHP的内置函数,通过DES算法对数据加密和解密相关文章请关注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