From 79fa6028d1b9cc30ad170470660f7ae4238c6a70 Mon Sep 17 00:00:00 2001 From: Divy Srivastava Date: Wed, 29 Jan 2025 20:49:43 +0530 Subject: [PATCH] fix(ext/node): implement `crypto.hash` (#27858) Implement [`crypto.hash`](https://nodejs.org/api/crypto.html#cryptohashalgorithm-data-outputencoding) - one-shot version of `createHash` Fixes #24945 --- ext/node/polyfills/crypto.ts | 12 ++++++++++++ tests/unit_node/crypto/crypto_hash_test.ts | 7 ++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/ext/node/polyfills/crypto.ts b/ext/node/polyfills/crypto.ts index ff3bdc7752..acea5c8629 100644 --- a/ext/node/polyfills/crypto.ts +++ b/ext/node/polyfills/crypto.ts @@ -169,6 +169,16 @@ function getRandomValues(typedArray) { return webcrypto.getRandomValues(typedArray); } +function hash( + algorithm: string, + data: BinaryLike, + outputEncoding: BinaryToTextEncoding = "hex", +) { + const hash = createHash(algorithm); + hash.update(data); + return hash.digest(outputEncoding); +} + function createCipheriv( algorithm: CipherCCMTypes, key: CipherKey, @@ -350,6 +360,7 @@ export default { getDiffieHellman, getFips, getHashes, + hash, Hash, hkdf, hkdfSync, @@ -489,6 +500,7 @@ export { getHashes, getRandomValues, Hash, + hash, hkdf, hkdfSync, Hmac, diff --git a/tests/unit_node/crypto/crypto_hash_test.ts b/tests/unit_node/crypto/crypto_hash_test.ts index 0a3fd2245e..5c0421a9eb 100644 --- a/tests/unit_node/crypto/crypto_hash_test.ts +++ b/tests/unit_node/crypto/crypto_hash_test.ts @@ -1,5 +1,5 @@ // Copyright 2018-2025 the Deno authors. MIT license. -import { createHash, createHmac, getHashes } from "node:crypto"; +import { createHash, createHmac, getHashes, hash } from "node:crypto"; import { Buffer } from "node:buffer"; import { Readable } from "node:stream"; import { assert, assertEquals } from "@std/assert"; @@ -127,3 +127,8 @@ Deno.test("[node/crypto.hash] does not leak", () => { const hasher = createHash("sha1"); hasher.update("abc"); }); + +Deno.test("[node/crypto.hash] oneshot hash API", () => { + const d = hash("sha1", "Node.js"); + assertEquals(d, "10b3493287f831e81a438811a1ffba01f8cec4b7"); +});