CryptoJS encrypt in aes-256-cbc returns an unexpected value

Ale*_*ais 5 javascript cryptojs

I am encrypting some data using CryptoJS and comparing it to an online tool and I am not getting the same result. In fact the result from CryptoJS in not decryptable with the tool.

I am trying to encrypt in AES-256-CBC with the following parameters:

text = '111222333'
iv = 'I8zyA4lVhMCaJ5Kg'
key = '6fa979f20126cb08aa645a8f495f6d85'
Run Code Online (Sandbox Code Playgroud)

Here's my code:

let text = '111222333';

aesEncrypt(data) {
    let key = '6fa979f20126cb08aa645a8f495f6d85';    //length 32
    let iv = 'I8zyA4lVhMCaJ5Kg';                     //length 16
    let cipher = CryptoJS.AES.encrypt(data, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return cipher.toString();
}

aesEncrypt(text);
Run Code Online (Sandbox Code Playgroud)

The resulting encrypted string is U2FsdGVkX1+f3UywYmIdtb50bzdxASRCSqB00OijOb0= while the one obtained with the online tool is B6AeMHPHkEe7/KHsZ6TW/Q==. Why are they different, I seem to be using the same parameters?

我使用 CryptoJS 的计划是加密一些数据客户端,然后在需要时能够在服务器端解密它。但是两个加密值的差异阻止了我这样做。

wee*_*gee 10

如何将您的数据编码为 UTF-8。就像“在线工具”所做的那样。

使用CryptoJS.enc.Utf8.parse 实现我在说什么。

aesEncrypt (data) {
   const key = '6fa979f20126cb08aa645a8f495f6d85'
   const iv = 'I8zyA4lVhMCaJ5Kg'
   
   const cipher = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
       iv: CryptoJS.enc.Utf8.parse(iv), // parse the IV 
       padding: CryptoJS.pad.Pkcs7,
       mode: CryptoJS.mode.CBC
   })
   
   // e.g. B6AeMHPHkEe7/KHsZ6TW/Q==
   return cipher.toString()
}
Run Code Online (Sandbox Code Playgroud)

使用 CryptoJS 的代码片段。

function aesEncrypt (data) {
   const key = '6fa979f20126cb08aa645a8f495f6d85'
   const iv = 'I8zyA4lVhMCaJ5Kg'
   const cipher = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
       iv: CryptoJS.enc.Utf8.parse(iv),
       padding: CryptoJS.pad.Pkcs7,
       mode: CryptoJS.mode.CBC
   })

   return cipher.toString()
}

// e.g. B6AeMHPHkEe7/KHsZ6TW/Q==
console.log(aesEncrypt('111222333'))
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/aes.js"></script>
Run Code Online (Sandbox Code Playgroud)

工作 Stackblitz 示例