首页 > 解决方案 > 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 中的任何配置?

谢谢

标签: node.jsreactjsencryption

解决方案


缺少 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>


推荐阅读