class MagicCrypt
{
// 密钥偏移量IV,可自定义
private $iv = '';
// AES-key,可自定义
private $encryptKey = '';
public function __construct($encryptKey, $iv)
{
$this->encryptKey = $encryptKey;
$this->iv = $iv;
}
/**
* 加密
* @param string $encryptStr
* @return string
*/
public function encrypt($encryptStr)
{
$localIV = $this->iv;
$encryptKey = $this->encryptKey;
// open module
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
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);
}
/**
* 解密
* @param string $encryptStr
* @return bool|string
*/
public function decrypt($encryptStr)
{
$localIV = $this->iv;
$encryptKey = $this->encryptKey;
// open module
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
mcrypt_generic_init($module, $encryptKey, $localIV);
$encryptedData = base64_decode($encryptStr);
$encryptedData = mdecrypt_generic($module, $encryptedData);
return $encryptedData;
}
}
Example:
$privateKey = '1234567890abcdef';
$iv = 'aes-cbc-iv';
$magicCrypt = new MagicCrypt($privateKey, $iv);
$encryptString = $magicCrypt->encrypt($encryptString);
$decryptString = $magicCrypt->decrypt($encryptString);
var_dump($encryptString);
var_dump($decryptString);
近期评论