前端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;
    }
}
相关推荐
万少6 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站8 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名11 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫11 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊11 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter11 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折11 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_11 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial12 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu12 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端