前端部分注意看填充是pkcs7
有个前提,要看前端有没有转成hex格式,如果没转,php那边就不需要调用特定函数转hex格式的
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代码
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必须为0function 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;}
}