diff --git a/lib/util/hash.spec.ts b/lib/util/hash.spec.ts new file mode 100644 index 00000000000000..813324b8cef27d --- /dev/null +++ b/lib/util/hash.spec.ts @@ -0,0 +1,12 @@ +import { hash, toSha256 } from './hash'; + +describe('util/hash', () => { + test('should hash data with sha256', () => { + expect(hash('https://example.com/test.txt', 'sha256')).toBe( + 'd1dc63218c42abba594fff6450457dc8c4bfdd7c22acf835a50ca0e5d2693020' + ); + expect(toSha256('https://example.com/test.txt')).toBe( + 'd1dc63218c42abba594fff6450457dc8c4bfdd7c22acf835a50ca0e5d2693020' + ); + }); +}); diff --git a/lib/util/hash.ts b/lib/util/hash.ts new file mode 100644 index 00000000000000..e6b079370cf659 --- /dev/null +++ b/lib/util/hash.ts @@ -0,0 +1,17 @@ +import crypto from 'node:crypto'; +import type { LiteralUnion } from 'type-fest'; + +export type AlgorithmName = LiteralUnion< + 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512', + string +>; + +export function hash(data: string | Buffer, algorithm: AlgorithmName): string { + const hash = crypto.createHash(algorithm); + hash.update(data); + return hash.digest('hex'); +} + +export function toSha256(input: string): string { + return hash(input, 'sha256'); +}