前端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;
    }
}
相关推荐
dy171738 分钟前
element-plus表格默认展开有子的数据
前端·javascript·vue.js
2501_915918414 小时前
Web 前端可视化开发工具对比 低代码平台、可视化搭建工具、前端可视化编辑器与在线可视化开发环境的实战分析
前端·低代码·ios·小程序·uni-app·编辑器·iphone
程序员的世界你不懂5 小时前
【Flask】测试平台开发,新增说明书编写和展示功能 第二十三篇
java·前端·数据库
索迪迈科技5 小时前
网络请求库——Axios库深度解析
前端·网络·vue.js·北京百思可瑞教育·百思可瑞教育
gnip5 小时前
JavaScript二叉树相关概念
前端
一朵梨花压海棠go6 小时前
html+js实现表格本地筛选
开发语言·javascript·html·ecmascript
attitude.x6 小时前
PyTorch 动态图的灵活性与实用技巧
前端·人工智能·深度学习
β添砖java6 小时前
CSS3核心技术
前端·css·css3
空山新雨(大队长)6 小时前
HTML第八课:HTML4和HTML5的区别
前端·html·html5