【问题标题】:Error: Unsupported state or unable to authenticate data错误:不受支持的状态或无法验证数据
【发布时间】:2021-04-29 00:40:56
【问题描述】:

我通过运行以下代码得到以下错误。

错误:不支持的状态或无法验证数据 在 Decipheriv.final (节点:internal/crypto/cipher:196:29) 在解密时(/Users/username/dev/playground/node/src/index.ts:14:65)

import crypto from "crypto";

const key = "13312156329479471107309870982123";

const encrypt = (message: string): string => {
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
  return `${cipher.update(message, "utf-8", "hex")}${cipher.final("hex")}`;
};

const decrypt = (message: string): string => {
  const iv = crypto.randomBytes(16);
  const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
  return `${decipher.update(message, "hex", "utf-8")}${decipher.final(
    "utf-8"
  )}`;
};

console.log(decrypt(encrypt("hello")));

我已经阅读了这些帖子

但我认为我不会因为同样的原因而遇到同样的错误。任何帮助,将不胜感激。谢谢

【问题讨论】:

    标签: node.js typescript encryption


    【解决方案1】:

    iv 需要对密码和解密都是通用的。应该阅读文档

    const key = crypto.randomBytes(32);
    const iv = crypto.randomBytes(16);
    
    const encrypt = (message: string): string => {
      const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
      return `${cipher.update(message, "utf-8", "hex")}${cipher.final("hex")}`;
    };
    
    const decrypt = (message: string): string => {
      const decipher = crypto.createDecipheriv("aes-256-cbc", key, iv);
      return `${decipher.update(message, "hex", "utf-8")}${decipher.final(
        "utf-8"
      )}`;
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 2018-06-07
      • 1970-01-01
      • 2020-06-26
      • 1970-01-01
      • 2022-11-30
      • 2014-02-11
      • 2017-08-03
      相关资源
      最近更新 更多