diff options
author | Matthew Miller <matthew@millerti.me> | 2022-11-13 07:40:50 -0800 |
---|---|---|
committer | Matthew Miller <matthew@millerti.me> | 2022-11-13 07:40:50 -0800 |
commit | f15dcada7c2ead3dd4124e1d53d8b0429614a213 (patch) | |
tree | 4bf8e2573ebe363d4f781ba58f96c6c169f274d1 | |
parent | dc0e0edeefc168700435c314a27020ff135d7020 (diff) |
Update toHash to use SubtleCrypto
-rw-r--r-- | packages/server/src/helpers/toHash.ts | 30 |
1 files changed, 24 insertions, 6 deletions
diff --git a/packages/server/src/helpers/toHash.ts b/packages/server/src/helpers/toHash.ts index 413e96f..64123df 100644 --- a/packages/server/src/helpers/toHash.ts +++ b/packages/server/src/helpers/toHash.ts @@ -1,13 +1,31 @@ -import crypto from 'crypto'; +import { webcrypto } from 'node:crypto'; + +import { isoUint8Array } from './iso'; /** * Returns hash digest of the given data using the given algorithm. * @param data Data to hash * @return The hash */ -// TODO: Made this async in preparation for trying to use globalThis.crypto (SubtleCrypto) to -// hash values, which returns a Promise -// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest -export async function toHash(data: Uint8Array | string, algo = 'SHA256'): Promise<Uint8Array> { - return crypto.createHash(algo).update(data).digest(); +export async function toHash(data: Uint8Array | string, algorithm = 'SHA-256'): Promise<Uint8Array> { + if (/sha\d{1,3}/i.test(algorithm)) { + // Convert algorithms like "SHA1", "SHA256", etc... into values like "SHA-1", "SHA-256", etc... + // that `.digest()` will accept + algorithm = algorithm.toUpperCase().replace('SHA', 'SHA-'); + } + + if (typeof data === 'string') { + data = isoUint8Array.fromUTF8String(data); + } + + let hashed: ArrayBuffer + if (globalThis.crypto) { + // We're in a browser-like runtime, use global Crypto + hashed = await globalThis.crypto.subtle.digest(algorithm, data); + } else { + // We're in Node, use Node's Crypto + hashed = await webcrypto.subtle.digest(algorithm, data); + } + + return new Uint8Array(hashed); } |