-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhash.ts
More file actions
44 lines (39 loc) · 1.02 KB
/
Copy pathhash.ts
File metadata and controls
44 lines (39 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { assertEquals } from "@std/assert/equals";
import { createHash } from "node:crypto";
import { decodeNixBase32 } from "./base32.ts";
import { splitOnce } from "./util.ts";
export class Hash {
raw: string;
algorithm: string;
hash: Uint8Array;
constructor(raw: string) {
this.raw = raw;
const [algorithm, encodedHash] = splitOnce(raw, ":");
this.algorithm = algorithm;
this.hash = decodeNixBase32(encodedHash);
}
createVerifierStream(): HashVerifierStream {
return new HashVerifierStream(this.algorithm, this.hash);
}
}
class HashVerifierStream extends TransformStream<Uint8Array, Uint8Array> {
constructor(
algorithm: string,
expectedHash: Uint8Array,
) {
const hasher = createHash(algorithm);
super({
transform(chunk, controller) {
hasher.update(chunk);
controller.enqueue(chunk);
},
flush() {
assertEquals(
new Uint8Array(hasher.digest()),
expectedHash,
`Hash mismatch`,
);
},
});
}
}