简体   繁体   English

从 CryptoJS 库迁移到 Web Crypto API

[英]Migrate from CryptoJS library to Web Crypto API

I need help migrating from CryptoJS to theWebCrypto API .我需要从CryptoJS迁移到WebCrypto API的帮助。 Currently, i'm encrypting like this using CryptoJS:目前,我正在使用 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();

But i didn't get it right trying to do this with WebCrypto API.但我没有正确尝试使用 WebCrypto API 来做到这一点。 I tried the following:我尝试了以下方法:

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")
);

All i'm trying to archive is a "simple" AES encryption which i can then decrypt backendside using PHP and openssl.我要存档的只是一个“简单”的 AES 加密,然后我可以使用 PHP 和 openssl 解密后端。

I figured it out.我想到了。 When you convert a CryptoJS encrypted Buffer .toString it makes a OpenSSL compatible Base64 string.当您转换 CryptoJS 加密缓冲区.toString时,它会生成与 OpenSSL 兼容的 Base64 字符串。 So all what was missing from my example above was converting the data object (byteArray) to a Base64 String.因此,我上面的示例中缺少的所有内容是将数据 object (byteArray) 转换为 Base64 字符串。 I did this using the following Code snippet:我使用以下代码片段做到了这一点:

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);
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM