php實現AES/CBC/PKCS5Padding加密解密(又叫:對稱加密)

今天在作一個和java程序接口的架接,java那邊須要我這邊(PHP)對傳過去的值進行AES對稱加密,接口返回的結果也是加密過的(就要用到解密),而後試了不少辦法,也一一對應了AES的key密鑰值,偏移量(IV)的值,都仍是不能和java加密解密的結果同樣,我很鬱悶,我很焦躁。接着我就去找了一些文檔,結果發現PHP裏面補碼方式只有:ZeroPadding這一種方式,而java接口那邊是用PKCS5Padding補碼方式,發現了問題所在,就編寫了以下PHP實現AES/CBC/PKCS5Padding的加密解密方式。若有錯誤,還請指正!下面貼出詳細代碼php

<?php

class MagicCrypt {
	private $iv = "0102030405060708";//密鑰偏移量IV,可自定義

	private $encryptKey = "自定義16位長度key";//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);

		return $encryptedData;
	}
}
$encryptString = 'gz1DR+BsCzQe55HFdq1IiQ==';
$encryptObj = new MagicCrypt();

$result = $encryptObj->encrypt($encryptString);//加密結果
$decryptString = $decryptString = $encryptObj->decrypt($result);//解密結果
echo $result . "<br/>";
echo $decryptString . "<br/>";
?>
相關文章
相關標籤/搜索