node.js - React 解密来自 NodeJS 的加密字符串
问题描述
我在 NodeJS 中使用创建了一个加密字符串crypto
节点JS:
const crypto = require('crypto');
const key = Buffer.from(SECRET_KEY, 'base64');
encrypt(text) {
const iv = crypto.randomBytes(16);
let cipher = crypto.createCipheriv(
'AES-128-CBC', key, iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([iv, encrypted, cipher.final()]);
return encrypted.toString('hex');
}
它运行良好,我无法更改 NodeJS。然后,我尝试使用 React 对其进行解密crypto-js
,但它返回一个空字符串。
var CryptoJS = require("crypto-js");
const KEY = SECRET_KEY;
export const decrypt = (text) => {
var bytes = CryptoJS.AES.decrypt(text, KEY);
return bytes.toString(CryptoJS.enc.Hex);
}
我是否缺少 React 中的任何配置?
谢谢
解决方案
缺少 CryptoJS 代码:
- IV和密文的分离。
- IV的规范。
- 适用于密文、密钥和 IV 的解码(使用相应的 CryptoJS 编码器)。
以下密文是使用 NodeJS 代码创建的:
d906539383bb4931c434d58daaf82dc95bc9d6833089a4fd0014b331060bc18fff2270b18c561cae36aebd48a82e9de5eaee31dc4ed059929fe37b9a468d9cdf
这可以用下面的 CryptoJS 代码解密:
const KEY = 'MDEyMzQ1Njc4OTAxMjM0NQ==';
function decrypt(text) {
// Separate IV and ciphertext
var iv = text.substring(0, 32);
var ciphertext = text.substring(32);
var bytes = CryptoJS.AES.decrypt(
{ciphertext: CryptoJS.enc.Hex.parse(ciphertext)},
CryptoJS.enc.Base64.parse(KEY),
{iv: CryptoJS.enc.Hex.parse(iv)}); // pass IV
return bytes.toString(CryptoJS.enc.Utf8); // or Hex as in the posted code
}
var encryptedData = 'd906539383bb4931c434d58daaf82dc95bc9d6833089a4fd0014b331060bc18fff2270b18c561cae36aebd48a82e9de5eaee31dc4ed059929fe37b9a468d9cdf';
console.log(decrypt(encryptedData)); // The quick brown fox jumps over the lazy dog
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
推荐阅读
- python - 如何遍历数据框以创建单独的 Folium 地图?
- bash - 从命名管道读取时如何停止 cat 命令?
- php - 无法在生产中下载laravel中的文件
- terraform - 在 terraform 中添加多个 azure sql 防火墙规则
- c++ - SSL 异常:无法在 POCO HTTPS 客户端中创建 SSL_CTX 对象
- android - 如何使用颤振将音频播放器添加到其中的应用程序大小小于 10 MB 的新闻最小化?
- sql - 编写一个 postgreSQL 查询来更新一个 json 列
- java - 在 androidx.appcompat.widget.SearchView 上设置建议
- java - java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“double java.lang.Double.doubleValue()”
- laravel - 带变量的 PHP 字符串