0

I'm getting the error below by running the following code.

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

I've read these posts

but I don't think that I'm getting the same error for the same reason. Any help would be appreciated. Thanks

Christopher
  • 97
  • 1
  • 10

1 Answers1

0

iv needed to be common for both cipher and decipher. Should have read the docs

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"
  )}`;
};
Christopher
  • 97
  • 1
  • 10