From 1b93263118633aff625b45639c00f2dfcc12b9a3 Mon Sep 17 00:00:00 2001
From: Adam Setch <adam.setch@outlook.com>
Date: Mon, 24 Jul 2023 00:40:56 -0400
Subject: [PATCH] feat: add hash util (#23524)

---
 lib/util/hash.spec.ts | 12 ++++++++++++
 lib/util/hash.ts      | 17 +++++++++++++++++
 2 files changed, 29 insertions(+)
 create mode 100644 lib/util/hash.spec.ts
 create mode 100644 lib/util/hash.ts

diff --git a/lib/util/hash.spec.ts b/lib/util/hash.spec.ts
new file mode 100644
index 0000000000..813324b8ce
--- /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 0000000000..e6b079370c
--- /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');
+}
-- 
GitLab