Error: Unsupported state or unable to authenticate data

Error: Unsupported state or unable to authenticate data

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

Error: Unsupported state or unable to authenticate data at Decipheriv.final (node:internal/crypto/cipher:196:29) at decrypt (/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")));

我已阅读这些帖子

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

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"
  )}`;
};