javascript - 从 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 加密缓冲区.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);
},
推荐阅读
- java - Spring Boot 中服务接口类的用途
- python - Scrapy - 使用选择器的嵌套链接提取
- javascript - 如何以遵循函数的方式制作动态 div 曲线?
- reactjs - 当组件重新渲染时,React 组件的状态会发生什么变化?
- functional-programming - Higher order function on lists Ocaml
- .htaccess - .htaccess 访问目录上传时重定向用户
- python - 在 matplotlib 中绘制体素图像
- docker - 如何从本地存储的源代码构建 yocto 分发,无需互联网访问
- azure-functions - Azure Functions 上使用的 Python Azure IoT SDK 无法将证书/密钥写入本地文件系统“只读”
- typescript - 错误:在导入 @applitools/eyes-selenium 时找不到模块“selenium-webdriver/package.json”