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

 前端部分注意看填充是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必须为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;
    }
}

你可能感兴趣的:(前端,javascript,AES,加密解密AES,php的AES加解密)