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