summaryrefslogtreecommitdiffhomepage
path: root/packages/util/src/encode.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/util/src/encode.ts')
-rw-r--r--packages/util/src/encode.ts25
1 files changed, 25 insertions, 0 deletions
diff --git a/packages/util/src/encode.ts b/packages/util/src/encode.ts
new file mode 100644
index 000000000..cc40fbe9d
--- /dev/null
+++ b/packages/util/src/encode.ts
@@ -0,0 +1,25 @@
+export function base64Encode(value: string) {
+ return btoa(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "")
+}
+
+export function base64Decode(value: string) {
+ return atob(value.replace(/-/g, "+").replace(/_/g, "/"))
+}
+
+export async function hash(content: string, algorithm = "SHA-256"): Promise<string> {
+ const encoder = new TextEncoder()
+ const data = encoder.encode(content)
+ const hashBuffer = await crypto.subtle.digest(algorithm, data)
+ const hashArray = Array.from(new Uint8Array(hashBuffer))
+ const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("")
+ return hashHex
+}
+
+export function checksum(content: string): string {
+ let hash = 0x811c9dc5
+ for (let i = 0; i < content.length; i++) {
+ hash ^= content.charCodeAt(i)
+ hash = Math.imul(hash, 0x01000193)
+ }
+ return (hash >>> 0).toString(36)
+}