由于对接第三方开放平台,官方提供的sdk的加解密方式是mcrypt AES 算法,使用了 32 位的秘钥和 16 位的向量,而现有系统环境是PHP7.2,mcrypt扩展已被弃用,需要换成openssl,在网上找了很多方法不成功,最后终于找到解决方法
mcrypt加解密:
<?php
class Prpcrypt
{
public $key;
function __construct($k)
{
$this->key = base64_decode($k . "=");
}
public function encrypt($text)
{
try {
// 网络字节序
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$iv = substr($this->key, 0, 16);
mcrypt_generic_init($module, $this->key, $iv);
//加密
$encrypted = mcrypt_generic($module, $text);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
//print(base64_encode($encrypted));
//使用BASE64对加密后的字符串进行编码
return base64_encode($encrypted);
} catch (Exception $e) {
print $e;
return false;
}
}
public function decrypt($encrypted)
{
try {
$ciphertext_dec = base64_decode($encrypted);
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
$iv = substr($this->key, 0, 16);
mcrypt_generic_init($module, $this->key, $iv);
$decrypted = mdecrypt_generic($module, $ciphertext_dec);
mcrypt_generic_deinit($module);
mcrypt_module_close($module);
} catch (Exception $e) {
return false;
}
return $decrypted;
}
function getRandomStr()
{
$str = "";
$str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$max = strlen($str_pol) - 1;
for ($i = 0; $i < 16; $i++) {
$str .= $str_pol[mt_rand(0, $max)];
}
return $str;
}
}
$k = "abc1237890123456789012345678901234567890abc";
$decrypStr = "hello";
$cryptObj = new Prpcrypt($k);
$ret = $cryptObj->encrypt($decrypStr);
$str = "SR4RIdC6WpiYS00yijC6Wg==";
$ret = $cryptObj->decrypt($str);
var_dump($ret);
openssl加解密
<?php
class Prpcrypt
{
public $key;
function __construct($k)
{
$this->key = base64_decode($k . "=");
}
public function encrypt($text)
{
try {
$iv = substr($this->key, 0, 16);
$encrypted = openssl_encrypt($text, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $iv);
} catch (Exception $e) {
print $e;
return false;
}
return base64_encode($encrypted);
}
public function decrypt($encrypted)
{
try {
$ciphertext_dec = base64_decode($encrypted);
$iv = substr($this->key, 0, 16);
$decrypted = openssl_decrypt($ciphertext_dec, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING,$iv);
} catch (Exception $e) {
return false;
}
return $decrypted;
}
function getRandomStr()
{
$str = "";
$str_pol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$max = strlen($str_pol) - 1;
for ($i = 0; $i < 16; $i++) {
$str .= $str_pol[mt_rand(0, $max)];
}
return $str;
}
}
$k = "abc1237890123456789012345678901234567890abc";
$decrypStr = "hello";
$cryptObj = new Prpcrypt($k);
$ret = $cryptObj->encrypt($decrypStr);
$str = "SR4RIdC6WpiYS00yijC6Wg==";
$ret = $cryptObj->decrypt($str);
var_dump($ret);