首页 > 解决方案 > 从 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 解密后端。

标签: javascriptcryptojswebcrypto-api

解决方案


我想到了。当您转换 CryptoJS 加密缓冲区.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);
},

推荐阅读