Skip to content

Commit

Permalink
feat: add hash util (#23524)
Browse files Browse the repository at this point in the history
  • Loading branch information
setchy committed Jul 24, 2023
1 parent 68e871e commit 1b93263
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
12 changes: 12 additions & 0 deletions 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'
);
});
});
17 changes: 17 additions & 0 deletions 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');
}

0 comments on commit 1b93263

Please sign in to comment.