首页 > 解决方案 > 我已经使用加密模块加密了 node.js 中的数据,如何使用 crypto-js 在 react.js 中解密

问题描述

在下面给出的 node.js 示例中,它工作正常,在 node.js 加密中使用 crypto 模块效果很好,但我不知道如何使用 crypto-js 库解密该数据。

const crypto = require('crypto');
const ENC_KEY = "6fa979f20126cb08aa645a8f495f6d85"; // set random encryption key
const IV = "7777777a72ddc2f1"; // set random initialisation vector

const phrase = "who let the dogs out";

var encrypt = ((val) => {
  let cipher = crypto.createCipheriv('aes-256-cbc', ENC_KEY, IV);
  let encrypted = cipher.update(val, 'utf8', 'base64');
  encrypted += cipher.final('base64');
  return encrypted;
});

var decrypt = ((encrypted) => {
  let decipher = crypto.createDecipheriv('aes-256-cbc', ENC_KEY, IV);
  let decrypted = decipher.update(encrypted, 'base64', 'utf8');
  return (decrypted + decipher.final('utf8'));
});

var encrypted_key = encrypt(phrase);
var original_phrase = decrypt(encrypted_key);
console.log(encrypted_key) // hUU10kfhDhOKA0jb4efuYq3BbtyiBl+EqhfYdTkSkiI=
console.log(original_phrase) // who let the dogs out

在反应中使用“crypto-js”,如何解密由 node.js 中的“crypto”模块完成的加密数据? 在反应中,我可以加密数据,

import CryptoJS from 'crypto-js'
aesEncrypt(data) {
    let key = '6fa979f20126cb08aa645a8f495f6d85';
    let iv = '7777777a72ddc2f1';
    let cipher = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        padding: CryptoJS.pad.Pkcs7,
        mode: CryptoJS.mode.CBC
    });
    console.log(cipher.toString()); 
}

标签: node.jsreactjsencryptionaes

解决方案


当您从后端获取加密数据时,只需在具有相同ENC_KEY的前端使用解密函数(与上述代码相同) 。它将返回解密的数据。


推荐阅读