前端CryptoJS-AES加解密 对应php的AES-128-CBC加解密踩坑(java也相同加解密)

前端部分注意看填充是pkcs7

有个前提,要看前端有没有转成hex格式,如果没转,php那边就不需要调用特定函数转hex格式的

javascript 复制代码
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代码

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必须为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;
    }
}
相关推荐
祈澈菇凉2 小时前
Webpack的基本功能有哪些
前端·javascript·vue.js
小纯洁w2 小时前
Webpack 的 require.context 和 Vite 的 import.meta.glob 的详细介绍和使用
前端·webpack·node.js
想睡好2 小时前
css文本属性
前端·css
qianmoQ2 小时前
第三章:组件开发实战 - 第五节 - Tailwind CSS 响应式导航栏实现
前端·css
记得早睡~3 小时前
leetcode150-逆波兰表达式求值
javascript·算法·leetcode
zhoupenghui1683 小时前
golang时间相关函数总结
服务器·前端·golang·time
White graces3 小时前
正则表达式效验邮箱格式, 手机号格式, 密码长度
前端·spring boot·spring·正则表达式·java-ee·maven·intellij-idea
庸俗今天不摸鱼3 小时前
Canvas进阶-4、边界检测(流光,鼠标拖尾)
开发语言·前端·javascript·计算机外设
bubusa~>_<3 小时前
解决npm install 出现error,比如:ERR_SSL_CIPHER_OPERATION_FAILED
前端·npm·node.js
[廾匸]4 小时前
cesium视频投影
javascript·无人机·cesium·cesium.js·视频投影