之前我們已經學習過了PHP實作DES加密解密 https://www.wj0511.com/site/detail.html?id=89
但是發現我在實作PHP實作DES加密解密時出現如下錯誤
Call to undefined function mcrypt_create_iv()
之後發現這是由于我們PHP版本原因,我的php版本是php7.2,如果我把我的php版本切換到php7.0就一切正常了,這是由于函數 mcrypt_get_iv_size 在隻在(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) 這幾個版本中有效,是以如果我們的php版本為php7.2的話,我們就需要使用openssl_encrypt函數來實作DES加密解密
1:建立一個DES加密解密元件
<?php
/**
* author: wangjian
* date: 2019/12/11
*/
namespace app\components;
class DesComponents
{
public $desKey;
public function __construct()
{
$this->desKey = '12345678';
}
//DES 加密
public function des($encrypt) {
$passcrypt = openssl_encrypt($encrypt, 'DES-ECB', $this->desKey, OPENSSL_RAW_DATA);
return $passcrypt;
}
/**
* 将二進制資料轉換成十六進制
*/
public function asc2hex($temp) {
return bin2hex ( $temp );
}
/**
* 十六進制轉換成二進制
*
* @param string
* @return string
*/
public function hex2asc($temp) {
$len = strlen ( $temp );
$data = '';
for($i = 0; $i < $len; $i += 2)
$data .= chr ( hexdec ( substr ( $temp, $i, 2 ) ) );
return $data;
}
//DES解密
public function un_des($decrypt) {
$cipher = openssl_decrypt(($decrypt), 'DES-ECB', $this->desKey, OPENSSL_RAW_DATA);
$cipher = trim($cipher);
return $cipher;
}
}
2:使用des加密解密
$message = '123456';//需要加密的資料
//加密
$des = new DesComponents();
$value = $des->des($message);
$value = $des->asc2hex($value);
var_dump($value);
echo '<br/>';
//解密
$value = $des->hex2asc($value);
$value = $des->un_des($value);
$value = trim($value);
var_dump($value);
上述的方法适合任何版本的php版本