denoland / deno

A modern runtime for JavaScript and TypeScript.
https://deno.com
MIT License
94.69k stars 5.26k forks source link

`node:crypto` `crypto.createCipheriv("aes-128-ecb", key, iv)` behaves differently from node #22053

Open ZYinMD opened 8 months ago

ZYinMD commented 8 months ago

Version: Deno 1.39.4

The following code involving node:crypto behaves differently from node:

$ node test.js
good!

$ deno run test.js
bad!

Possibly related: #18412 @kt3k

Possible culprit is the iv argument.

// test.js

import crypto from "node:crypto";
import { Buffer } from "node:buffer"; // this line is optional when using node

const key = "1234567890ABCDEF";

const iv = ""; // node outputs "good!", deno outputs "bad!"

// const iv = null; // node outputs "good!", deno throws

// const iv = new Uint8Array(16); // node throws, deno outputs "bad!"

export function encrypt(plainText) {
  const cipher = crypto.createCipheriv("aes-128-ecb", key, iv);
  return Buffer.concat([
    cipher.update(plainText),
    cipher.final(),
  ]).toString("base64");
}

export function decrypt(cipherText) {
  const cipher = crypto.createDecipheriv("aes-128-ecb", key, iv);
  return Buffer.concat([
    cipher.update(Buffer.from(cipherText, "base64")),
    cipher.final(),
  ]).toString("utf8");
}

const original = "hello world!";
const encrypted = encrypt(original); // "uMslN/bVLTsD2u4iu8v2fA=="
const decrypted = decrypt(encrypted); // "hello world!"

console.log(original === decrypted ? "good!" : "bad!");
littledivy commented 6 months ago

Ref https://github.com/denoland/deno/issues/22988