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.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/backend/sha1.ts
Views: 687
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
if (typeof data === "string") {
10
// CRITICAL: Code below assumes data is a Buffer; it will seem to work on a string, but give
11
// the wrong result where wrong means that it doesn't agree with the frontend version defined
12
// in misc.
13
data = Buffer.from(data);
14
}
15
const sha1sum = createHash("sha1");
16
sha1sum.update(data);
17
return sha1sum.digest("hex");
18
}
19
20
// Compute a uuid v4 from the Sha-1 hash of data.
21
// Optionally, if knownSha1 is given, just uses that, rather than recomputing it.
22
export function uuidsha1(data: Buffer | string, knownSha1?: string): string {
23
const s = knownSha1 ?? sha1(data);
24
let i = -1;
25
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
26
i += 1;
27
switch (c) {
28
case "x":
29
return s[i] ?? "0";
30
case "y":
31
// take 8 + low order 3 bits of hex number.
32
return ((parseInt("0x" + s[i], 16) & 0x3) | 0x8).toString(16);
33
}
34
return "0";
35
});
36
}
37
38