This repository has been archived by the owner on Feb 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 183
/
Copy pathhash.ts
70 lines (53 loc) · 1.58 KB
/
hash.ts
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { _heap_write } from '../other/utils';
import { IllegalStateError } from '../other/errors';
import { sha1result } from './sha1/sha1.asm';
import { sha256result } from './sha256/sha256.asm';
import { sha512result } from './sha512/sha512.asm';
export abstract class Hash<T extends sha1result | sha256result | sha512result> {
public result!: Uint8Array | null;
public pos: number = 0;
public len: number = 0;
public asm!: T;
public heap!: Uint8Array;
public BLOCK_SIZE!: number;
public HASH_SIZE!: number;
reset() {
this.result = null;
this.pos = 0;
this.len = 0;
this.asm.reset();
return this;
}
process(data: Uint8Array) {
if (this.result !== null) throw new IllegalStateError('state must be reset before processing new data');
let asm = this.asm;
let heap = this.heap;
let hpos = this.pos;
let hlen = this.len;
let dpos = 0;
let dlen = data.length;
let wlen = 0;
while (dlen > 0) {
wlen = _heap_write(heap, hpos + hlen, data, dpos, dlen);
hlen += wlen;
dpos += wlen;
dlen -= wlen;
wlen = asm.process(hpos, hlen);
hpos += wlen;
hlen -= wlen;
if (!hlen) hpos = 0;
}
this.pos = hpos;
this.len = hlen;
return this;
}
finish() {
if (this.result !== null) throw new IllegalStateError('state must be reset before processing new data');
this.asm.finish(this.pos, this.len, 0);
this.result = new Uint8Array(this.HASH_SIZE);
this.result.set(this.heap.subarray(0, this.HASH_SIZE));
this.pos = 0;
this.len = 0;
return this;
}
}