Skip to content

Commit

Permalink
fix(ext/node): implement crypto.hash (#27858)
Browse files Browse the repository at this point in the history
Implement
[`crypto.hash`](https://nodejs.org/api/crypto.html#cryptohashalgorithm-data-outputencoding)
- one-shot version of `createHash`

Fixes #24945
  • Loading branch information
littledivy authored Jan 29, 2025
1 parent 0098fdd commit 79fa602
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
12 changes: 12 additions & 0 deletions ext/node/polyfills/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -350,6 +360,7 @@ export default {
getDiffieHellman,
getFips,
getHashes,
hash,
Hash,
hkdf,
hkdfSync,
Expand Down Expand Up @@ -489,6 +500,7 @@ export {
getHashes,
getRandomValues,
Hash,
hash,
hkdf,
hkdfSync,
Hmac,
Expand Down
7 changes: 6 additions & 1 deletion tests/unit_node/crypto/crypto_hash_test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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");
});

0 comments on commit 79fa602

Please sign in to comment.