Branchwell

Branchwell / source / src / git / sha1.ts

1// Incremental SHA-1 (Git object ids and pack trailers). WebCrypto is one-shot, packs stream.
2export class Sha1 {
3 private h = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]);
4 private buf = new Uint8Array(64);
5 private bufLen = 0;
6 private total = 0;
7 private w = new Uint32Array(80);
8
9 update(data: Uint8Array): this {
10 let i = 0;
11 this.total += data.length;
12 if (this.bufLen) {
13 const n = Math.min(64 - this.bufLen, data.length);
14 this.buf.set(data.subarray(0, n), this.bufLen);
15 this.bufLen += n; i = n;
16 if (this.bufLen === 64) { this.block(this.buf, 0); this.bufLen = 0; }
17 }
18 for (; i + 64 <= data.length; i += 64) this.block(data, i);
19 if (i < data.length) { this.buf.set(data.subarray(i), 0); this.bufLen = data.length - i; }
20 return this;
21 }
22
23 digest(): Uint8Array {
24 const bits = this.total * 8;
25 const pad = new Uint8Array(((this.bufLen < 56 ? 56 : 120) - this.bufLen) + 8);
26 pad[0] = 0x80;
27 const dv = new DataView(pad.buffer);
28 dv.setUint32(pad.length - 8, Math.floor(bits / 0x100000000));
29 dv.setUint32(pad.length - 4, bits >>> 0);
30 this.total -= pad.length; // padding is not message data
31 this.update(pad);
32 const out = new Uint8Array(20);
33 const o = new DataView(out.buffer);
34 for (let k = 0; k < 5; k++) o.setUint32(k * 4, this.h[k]);
35 return out;
36 }
37
38 private block(d: Uint8Array, off: number) {
39 const w = this.w;
40 for (let t = 0; t < 16; t++) w[t] = (d[off + t * 4] << 24) | (d[off + t * 4 + 1] << 16) | (d[off + t * 4 + 2] << 8) | d[off + t * 4 + 3];
41 for (let t = 16; t < 80; t++) { const x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]; w[t] = (x << 1) | (x >>> 31); }
42 let [a, b, c, dd, e] = this.h;
43 for (let t = 0; t < 80; t++) {
44 let f: number, k: number;
45 if (t < 20) { f = (b & c) | (~b & dd); k = 0x5a827999; }
46 else if (t < 40) { f = b ^ c ^ dd; k = 0x6ed9eba1; }
47 else if (t < 60) { f = (b & c) | (b & dd) | (c & dd); k = 0x8f1bbcdc; }
48 else { f = b ^ c ^ dd; k = 0xca62c1d6; }
49 const tmp = (((a << 5) | (a >>> 27)) + f + e + k + w[t]) >>> 0;
50 e = dd; dd = c; c = (b << 30) | (b >>> 2); b = a; a = tmp;
51 }
52 this.h[0] = (this.h[0] + a) >>> 0; this.h[1] = (this.h[1] + b) >>> 0; this.h[2] = (this.h[2] + c) >>> 0;
53 this.h[3] = (this.h[3] + dd) >>> 0; this.h[4] = (this.h[4] + e) >>> 0;
54 }
55}
56
57export const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
58export const unhex = (s: string) => { const o = new Uint8Array(s.length / 2); for (let i = 0; i < o.length; i++) o[i] = parseInt(s.substr(i * 2, 2), 16); return o; };