AES-ECB-128 pkcs5填充加解密
class AesEncryptService
{
/**
* @desc AES-128-ECB加密
* @param $str
* @param $encryptKey
* @return string
*/
public static function AesEncrypt($str, $encryptKey)
{
if (version_compare(PHP_VERSION, '7.1.0', '<')) {
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$input = self::addPKCS5Padding($str, $size);
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $encryptKey, $iv);
$data = mcrypt_generic($td, $input);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
} else {
$data = openssl_encrypt($str, 'AES-128-ECB', $encryptKey, OPENSSL_RAW_DATA);
}
$data = base64_encode($data);
return $data;
}
/**
* @desc 添加PKCS5填充
* @param $source
* @param $size
* @return string
*/
private static function addPKCS5Padding($source, $size)
{
$pad = $size - (strlen($source) % $size);
return $source . str_repeat(chr($pad), $pad);
}
/**
* @desc 去除PKCS5填充
* @param $decrypted
* @return string
*/
private static function unsetPKCS5Padding($decrypted)
{
$dec_s = strlen($decrypted);
$padding = ord($decrypted[$dec_s - 1]);
$decrypted = substr($decrypted, 0, -$padding);
return $decrypted;
}
/**
* @desc AES-128-ECB解密方法
* @param string $str
* @param string $encryptKey
* @return string
*/
public static function AesDecrypt( $str, $encryptKey)
{
if (version_compare(PHP_VERSION, '7.1.0', '<')) {
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $encryptKey, base64_decode($str), MCRYPT_MODE_ECB);
$decrypted = self::unsetPKCS5Padding($decrypted);
} else {
$decrypted = openssl_decrypt($str, 'AES-128-ECB', $encryptKey, OPENSSL_RAW_DATA);
}
return $decrypted;
}
}
来源:https://blog.csdn.net/qq_39209296/article/details/100972471