从 CryptoJS 库迁移到 Web Crypto API

问题描述

我需要帮助从 CryptoJS 迁移到 WebCrypto API。 目前,我正在使用 CryptoJS 进行这样的加密:

let data = global.CryptoJS.AES.encrypt(
     "Data to encrypt",global.CryptoJS.enc.latin1.parse("encryption_key"),{
         iv : global.CryptoJS.enc.latin1.parse("1234567891123456"),mode : global.CryptoJS.mode.CBC
     }
).toString();

但是我没有正确地尝试使用 WebCrypto API 来做到这一点。我尝试了以下方法

let key = await window.crypto.subtle.importKey(
     "raw",(new TextEncoder().encode("encryption_key")),"AES-CBC",true,["encrypt","decrypt"]
);

let data = await window.crypto.subtle.encrypt(
   {
     name: 'AES-CBC',iv: new TextEncoder().encode("1234567891123456")
   },key,new TextEncoder().encode("Data to encrypt")
);

我想要存档的只是一个“简单”的 AES 加密,然后我可以使用 PHP 和 openssl 解密后端。

解决方法

我想通了。当您转换 CryptoJS 加密的 Buffer .toString 时,它会生成与 OpenSSL 兼容的 Base64 字符串。因此,我上面的示例中缺少的所有内容是将数据对象 (byteArray) 转换为 Base64 字符串。我使用以下代码片段做到了这一点:

byteArrayToBase64 = function byteArrayToBase64(array)
{
    let u_binary = '';
    let u_bytes = new Uint8Array( array );
    let u_len = u_bytes.byteLength;
    for (let i = 0; i < u_len; i++) {
        u_binary += String.fromCharCode(u_bytes[i]);
    }

    return btoa(u_binary);
},