配合java程序接口的架接,java那边需要我这边对传过去的值进行AES对称加密,接口返回的结果也是加密过的(就要用到解密),然后试了很多办法,也一一对应了AES的key密钥值,偏移量(IV)的值,都还是不能和java加密解密的结果一样。接着我就去找了一些文档,结果发现PHP里面补码方式只有:ZeroPadding这一种方式,而java接口那边是用PKCS5Padding补码方式,发现了问题所在,就编写了如下PHP实现AES/CBC/PKCS5Padding的加密解密方式。如有错误,还请指正!
1 <?php 2 3 class MagicCrypt { 4 private $iv = "0102030405060708";//密钥偏移量IV,可自定义 5 6 private $encryptKey = "自定义16位长度key";//AESkey,可自定义 7 8 //加密 9 public function encrypt($encryptStr) { 10 $localIV = $this->iv; 11 $encryptKey = $this->encryptKey; 12 13 //Open module 14 $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV); 15 16 //print "module = $module <br/>" ; 17 18 mcrypt_generic_init($module, $encryptKey, $localIV); 19 20 //Padding 21 $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); 22 $pad = $block - (strlen($encryptStr) % $block); //Compute how many characters need to pad 23 $encryptStr .= str_repeat(chr($pad), $pad); // After pad, the str length must be equal to block or its integer multiples 24 25 //encrypt 26 $encrypted = mcrypt_generic($module, $encryptStr); 27 28 //Close 29 mcrypt_generic_deinit($module); 30 mcrypt_module_close($module); 31 32 return base64_encode($encrypted); 33 34 } 35 36 //解密 37 public function decrypt($encryptStr) { 38 $localIV = $this->iv; 39 $encryptKey = $this->encryptKey; 40 41 //Open module 42 $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV); 43 44 //print "module = $module <br/>" ; 45 46 mcrypt_generic_init($module, $encryptKey, $localIV); 47 48 $encryptedData = base64_decode($encryptStr); 49 $encryptedData = mdecrypt_generic($module, $encryptedData); 50 51 return $encryptedData; 52 } 53 } 54 $encryptString = 'gz1DR+BsCzQe55HFdq1IiQ=='; 55 $encryptObj = new MagicCrypt(); 56 57 $result = $encryptObj->encrypt($encryptString);//加密结果 58 $decryptString = $decryptString = $encryptObj->decrypt($result);//解密结果 59 echo $result . "<br/>"; 60 echo $decryptString . "<br/>"; 61 ?>