Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kentcdodds/google

Google helpers for Gmail, Calendar, Drive, People, YouTube (including upload), and Analytics.

FollowFork

Files

sha256.ts

122 lines · 4.9 KB · TypeScript
// Vendored verbatim from @kody/youtube src/internal (keep in sync; no kody: dependency so this public package stays self-contained).
/**
 * Incremental SHA-256 whose midstate can be checkpointed. WebCrypto has no
 * streaming digest, and an upload that resumes after a crash must keep hashing
 * from the last acknowledged byte without re-reading the whole source.
 *
 * A state is serializable only on a 64-byte block boundary (resumable upload
 * chunks are multiples of 256 KiB, so every non-final acknowledgement is).
 * Self-contained so @kody/youtube and @kentcdodds/google can vendor it as-is.
 */

const K = new Uint32Array([
	0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
	0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
	0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85,
	0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
	0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
	0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
])
const INITIAL = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]

/** JSON-safe midstate: eight 32-bit words and the number of bytes hashed. */
export type Sha256State = { h: number[]; bytes: number }

export class Sha256 {
	private h: Uint32Array
	private bytes: number
	private buf = new Uint8Array(64)
	private bufLen = 0
	private w = new Uint32Array(64)
	private done = false

	constructor(state?: Sha256State) {
		if (state) {
			if (!Array.isArray(state.h) || state.h.length !== 8 || !Number.isSafeInteger(state.bytes) || state.bytes < 0 || state.bytes % 64 !== 0) {
				throw new Error('Invalid SHA-256 checkpoint state.')
			}
			this.h = Uint32Array.from(state.h)
			this.bytes = state.bytes
		} else {
			this.h = Uint32Array.from(INITIAL)
			this.bytes = 0
		}
	}

	get bytesHashed(): number {
		return this.bytes + this.bufLen
	}

	update(data: Uint8Array): this {
		if (this.done) throw new Error('SHA-256 already finalized.')
		let i = 0
		if (this.bufLen) {
			const take = Math.min(64 - this.bufLen, data.length)
			this.buf.set(data.subarray(0, take), this.bufLen)
			this.bufLen += take
			i = take
			if (this.bufLen === 64) {
				this.block(this.buf, 0)
				this.bytes += 64
				this.bufLen = 0
			}
		}
		for (; i + 64 <= data.length; i += 64) {
			this.block(data, i)
			this.bytes += 64
		}
		if (i < data.length) {
			this.buf.set(data.subarray(i), 0)
			this.bufLen = data.length - i
		}
		return this
	}

	/** Checkpoint; only valid on a 64-byte boundary. */
	snapshot(): Sha256State {
		if (this.bufLen !== 0) throw new Error('SHA-256 state can only be checkpointed on a 64-byte boundary.')
		return { h: Array.from(this.h), bytes: this.bytes }
	}

	digestHex(): string {
		if (this.done) throw new Error('SHA-256 already finalized.')
		this.done = true
		const totalBits = (this.bytes + this.bufLen) * 8
		const pad = new Uint8Array(this.bufLen < 56 ? 64 : 128)
		pad.set(this.buf.subarray(0, this.bufLen))
		pad[this.bufLen] = 0x80
		const view = new DataView(pad.buffer)
		view.setUint32(pad.length - 8, Math.floor(totalBits / 2 ** 32))
		view.setUint32(pad.length - 4, totalBits >>> 0)
		for (let o = 0; o < pad.length; o += 64) this.block(pad, o)
		return Array.from(this.h, (x) => x.toString(16).padStart(8, '0')).join('')
	}

	private block(data: Uint8Array, off: number) {
		const w = this.w
		for (let t = 0; t < 16; t++) {
			const j = off + t * 4
			w[t] = (data[j] << 24) | (data[j + 1] << 16) | (data[j + 2] << 8) | data[j + 3]
		}
		for (let t = 16; t < 64; t++) {
			const a = w[t - 15]
			const b = w[t - 2]
			const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3)
			const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10)
			w[t] = (w[t - 16] + s0 + w[t - 7] + s1) | 0
		}
		const h = this.h
		let a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7]
		for (let t = 0; t < 64; t++) {
			const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7))
			const ch = (e & f) ^ (~e & g)
			const t1 = (hh + S1 + ch + K[t] + w[t]) | 0
			const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10))
			const maj = (a & b) ^ (a & c) ^ (b & c)
			const t2 = (S0 + maj) | 0
			hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0
		}
		h[0] = (h[0] + a) | 0; h[1] = (h[1] + b) | 0; h[2] = (h[2] + c) | 0; h[3] = (h[3] + d) | 0
		h[4] = (h[4] + e) | 0; h[5] = (h[5] + f) | 0; h[6] = (h[6] + g) | 0; h[7] = (h[7] + hh) | 0
	}
}