// Incremental SHA-1 (Git object ids and pack trailers). WebCrypto is one-shot, packs stream. export class Sha1 { private h = new Uint32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]); private buf = new Uint8Array(64); private bufLen = 0; private total = 0; private w = new Uint32Array(80); update(data: Uint8Array): this { let i = 0; this.total += data.length; if (this.bufLen) { const n = Math.min(64 - this.bufLen, data.length); this.buf.set(data.subarray(0, n), this.bufLen); this.bufLen += n; i = n; if (this.bufLen === 64) { this.block(this.buf, 0); this.bufLen = 0; } } for (; i + 64 <= data.length; i += 64) this.block(data, i); if (i < data.length) { this.buf.set(data.subarray(i), 0); this.bufLen = data.length - i; } return this; } digest(): Uint8Array { const bits = this.total * 8; const pad = new Uint8Array(((this.bufLen < 56 ? 56 : 120) - this.bufLen) + 8); pad[0] = 0x80; const dv = new DataView(pad.buffer); dv.setUint32(pad.length - 8, Math.floor(bits / 0x100000000)); dv.setUint32(pad.length - 4, bits >>> 0); this.total -= pad.length; // padding is not message data this.update(pad); const out = new Uint8Array(20); const o = new DataView(out.buffer); for (let k = 0; k < 5; k++) o.setUint32(k * 4, this.h[k]); return out; } private block(d: Uint8Array, off: number) { const w = this.w; 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]; 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); } let [a, b, c, dd, e] = this.h; for (let t = 0; t < 80; t++) { let f: number, k: number; if (t < 20) { f = (b & c) | (~b & dd); k = 0x5a827999; } else if (t < 40) { f = b ^ c ^ dd; k = 0x6ed9eba1; } else if (t < 60) { f = (b & c) | (b & dd) | (c & dd); k = 0x8f1bbcdc; } else { f = b ^ c ^ dd; k = 0xca62c1d6; } const tmp = (((a << 5) | (a >>> 27)) + f + e + k + w[t]) >>> 0; e = dd; dd = c; c = (b << 30) | (b >>> 2); b = a; a = tmp; } this.h[0] = (this.h[0] + a) >>> 0; this.h[1] = (this.h[1] + b) >>> 0; this.h[2] = (this.h[2] + c) >>> 0; this.h[3] = (this.h[3] + dd) >>> 0; this.h[4] = (this.h[4] + e) >>> 0; } } export const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join(''); export 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; };