前端部分注意看填充是pkcs7
有个前提,要看前端有没有转成hex格式,如果没转,php那边就不需要调用特定函数转hex格式的文章来源:https://www.toymoban.com/news/detail-615009.html
const keyStr = '5hOwdHxpW0GOciqZ';
const iv = '0102030405060708';
//加密
function Encrypt(word) {
let key = CryptoJS.enc.Utf8.parse(keyStr);
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: CryptoJS.enc.Utf8.parse(iv),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
let hexStr = encrypted.ciphertext.toString().toUpperCase();
return hexStr.toString();
// encrypted.ciphertext.toString(); // 返回hex格式的密文
//encrypted.toString(); //此方式返回base64格式密文
}
//解密
function Decrypt(word) {
let key = CryptoJS.enc.Utf8.parse(keyStr);
let encryptedHexStr = CryptoJS.enc.Hex.parse(word);
var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
let decrypt = CryptoJS.AES.decrypt(srcs, key, {
iv: CryptoJS.enc.Utf8.parse(iv),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
后端php代码文章来源地址https://www.toymoban.com/news/detail-615009.html
if (!function_exists('encrypt')) {
//加密
function encrypt($data, $method = 'AES-128-CBC', $typeNum = 1)
{
$key = '5hOwdHxpW0GOciqZ';
$iv = '0102030405060708';
$a = openssl_encrypt($data, $method, $key, $typeNum, $iv);
// $base64 = base64_encode(openssl_encrypt($data, $method, $key, $typeNum, $iv));
//先转hex格式 再转大写模式
return strtoupper(bin2hex($a));
}
}
if (!function_exists('decrypt')) {
//解密 这里 $typeNum必须为0
function decrypt($data, $method = "AES-128-CBC", $typeNum = 0)
{
$key = '5hOwdHxpW0GOciqZ';
$iv = '0102030405060708';
$data = base64_encode(hex2bin($data));
$a = openssl_decrypt($data, $method, $key, $typeNum, $iv);
return $a;
}
}
到了这里,关于前端CryptoJS-AES加解密 对应php的AES-128-CBC加解密踩坑(java也相同加解密)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!