CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/backend/sha1.ts
Views: 1011
1
/*
2
sha1 hash functionality
3
*/
4
5
import { createHash } from "crypto";
6
7
// compute sha1 hash of data in hex
8
export function sha1(data: Buffer | string): string {
9
const sha1sum = createHash("sha1");
10
11
if (typeof data === "string") {
12
sha1sum.update(data, "utf8");
13
} else {
14
// Convert Buffer to Uint8Array
15
const uint8Array = new Uint8Array(
16
data.buffer,
17
data.byteOffset,
18
data.byteLength,
19
);
20
sha1sum.update(uint8Array);
21
}
22
23
return sha1sum.digest("hex");
24
}
25
26
// Compute a uuid v4 from the Sha-1 hash of data.
27
// Optionally, if knownSha1 is given, just uses that, rather than recomputing it.
28
export function uuidsha1(data: Buffer | string, knownSha1?: string): string {
29
const s = knownSha1 ?? sha1(data);
30
let i = -1;
31
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
32
i += 1;
33
switch (c) {
34
case "x":
35
return s[i] ?? "0";
36
case "y":
37
// take 8 + low order 3 bits of hex number.
38
return ((parseInt("0x" + s[i], 16) & 0x3) | 0x8).toString(16);
39
}
40
return "0";
41
});
42
}
43
44