php实现AES/CBC/PKCS5Padding加密解密(又叫:对称加密)
配合java程序接口的架接,java那边需要我这边对传过去的值进行AES对称加密,接口返回的结果也是加密过的(就要用到解密),然后试了很多办法,也一一对应了AES的key密钥值,偏移量(IV)的值,都还是不能和java加密解密的结果一样。接着我就去找了一些文档,结果发现PHP里面补码方式只有:ZeroPadding这一种方式,而java接口那边是用PKCS5Padding补码方式,发现了问题所在,就编写了如下PHP实现AES/CBC/PKCS5Padding的加密解密方式。如有错误,还请指正!
对接农业银行接口的数据加密
class MagicCrypt {
private $iv = "9457e5f423704b15";//密钥偏移量IV,可自定义
private $encryptKey = "cff054d1d7c84036a3dc160f";//AESkey,可自定义
//加密
public function encrypt($encryptStr) {
$localIV = $this->iv;
$encryptKey = $this->encryptKey;
//Open module
$module = @mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
//print "module = $module <br/>" ;
@mcrypt_generic_init($module, $encryptKey, $localIV);
//Padding
$block = @mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$pad = $block - (strlen($encryptStr) % $block); //Compute how many characters need to pad
$encryptStr .= str_repeat(chr($pad), $pad); // After pad, the str length must be equal to block or its integer multiples
//encrypt
$encrypted = @mcrypt_generic($module, $encryptStr);
//Close
@mcrypt_generic_deinit($module);
@mcrypt_module_close($module);
return base64_encode($encrypted);
}
//解密
public function decrypt($encryptStr) {
$localIV = $this->iv;
$encryptKey = $this->encryptKey;
//Open module
$module = @mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
//print "module = $module <br/>" ;
@mcrypt_generic_init($module, $encryptKey, $localIV);
$encryptedData = base64_decode($encryptStr);
$encryptedData = @mdecrypt_generic($module, $encryptedData);
//去补码,缺少这个PHP解密后面会有问号乱码
$pad = ord($encryptedData{strlen($encryptedData) - 1});
if ($pad > strlen($encryptedData)) {
return false;
}
return substr($encryptedData, 0, -1 * $pad);
}
}
参考https://www.cnblogs.com/lonmyblog/p/7885974.html