首页 > 解决方案 > 在使用加密进行解密时,使用 Node.js 得到错误的解密错误

问题描述

我以加密格式将信息存储在数据库中。当我从数据库中检索它并对其应用解密时,我收到类似“错误解密”的错误

这是我的代码:

const crypto = require("crypto");
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

function encrypt(text) {
  let cipher = crypto.createCipheriv("aes-256-cbc", Buffer.from(key), iv);
  let encrypted = cipher.update(text);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return { iv: iv.toString("hex"), encryptedData: encrypted.toString("hex") };
}

function decrypt(text) {
  let iv = Buffer.from(text.iv, "hex");
  let encryptedText = Buffer.from(text.encryptedData, "hex");
  let decipher = crypto.createDecipheriv("aes-256-cbc", Buffer.from(key), iv);
  let decrypted = decipher.update(encryptedText);
  decrypted = Buffer.concat([decrypted, decipher.final()]);
  return decrypted.toString();
}

/********** following is the api **************/
exports.viewTrade = async (req, res) => {
  console.log("viewTrade api ", req.query);
  let maindData = [];
  var hw = {
    iv: "fc4ca9a17d97d7a7772449cfea3a99b8",
    encryptedData: "e966509fd17785b4fe8304ef2f531806",
  };
  console.log(decrypt(hw));

  const tradeList = await trade.find({
    createdBy: req.query.id,
  });

  if (tradeList.length) {
    for (tradeInfo of tradeList) {
      // let nameInfo = tradeInfo.name;
      // // let value = decrypt(nameInfo);
      // console.log("name info.. ", nameInfo);
      // // console.log("value.. ", value);
    }
  }
};

通过调用上述 API,它会抛出错误。

标签: node.jscryptography

解决方案


当我尝试您的代码时,我收到如下错误:错误:06065064:数字信封例程:EVP_DecryptFinal_ex:错误解密。

这可能意味着用于解密的密钥与加密密钥不同。

我怀疑这是因为上面的代码在每次运行时都会重新创建密钥。

我建议您使用固定密钥,可能来自环境变量或安全机密存储。要对此进行测试,您可以像这样初始化密钥:

const key = Buffer.from("232f150296ffd446fc0b39fa32d1c1d42c2e232ccd3203df729b7f3c3c63a5da2", "hex");

然后加密一条消息,看看它会像这样正确解密:

const encrypted = encrypt("We love Stack Overflow");
const decrypted = decrypt(encrypted);

console.log("encrypted data:", encrypted);
console.log("decrypted data:", decrypted);

您会注意到,如果您将加密数据从程序的一次运行复制到下一次,它应该使用固定密钥,但如果您在每次运行时生成密钥,则会出现 bad_decrypt 错误。

密钥生成代码:

 const key = crypto.randomBytes(32).toString("hex"); 

推荐阅读