我使用 crypto
NodeJS:
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 中的任何配置?
谢谢
答案 0 :(得分:2)
缺少 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>