171 lines
7.7 KiB
JavaScript
171 lines
7.7 KiB
JavaScript
/* ============================================================================
|
|
* sha256.js — incremental SHA-256 (pure JS; window.Sha256 / worker / node)
|
|
*
|
|
* The block function runs as WebAssembly (wasm/sha256.c → sha256-wasm.js) when the
|
|
* browser allows it, with the pure-JS version below as the fallback — a failed
|
|
* load or a failed self-test silently keeps hashing in JS.
|
|
*
|
|
* WebCrypto's digest() needs the whole input at once, which would pull a
|
|
* multi-hundred-MB video into memory. This hasher takes chunks as they stream
|
|
* past (downloads, peer transfers, OPFS reads) and keeps ~100 bytes of state.
|
|
*
|
|
* const h = Sha256.create(); h.update(u8); …; const hex = h.hex();
|
|
* Sha256.hex(u8) // one-shot convenience
|
|
* ========================================================================== */
|
|
(function (root) {
|
|
'use strict';
|
|
|
|
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,
|
|
]);
|
|
|
|
// ---- WebAssembly engine (optional) -------------------------------------
|
|
// Memory layout shared with wasm/sha256.c: state at STATE, input blocks at DATA.
|
|
const STATE = 16384, DATA = 65536, CHUNK = 1 << 20; // 1 MiB staging window
|
|
const IV = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
|
|
let wasm; // undefined = not tried yet, null = unavailable, else { compress, state, data }
|
|
function loadWasm() {
|
|
if (wasm !== undefined) return wasm;
|
|
wasm = null;
|
|
try {
|
|
if (typeof WebAssembly === 'undefined') return wasm;
|
|
if (!root.SHA256_WASM_B64 && typeof importScripts === 'function') importScripts(root.__ASSET_URLS__?.wasm || '/sha256-wasm.js');
|
|
let b64 = root.SHA256_WASM_B64;
|
|
if (!b64 && typeof require === 'function') b64 = require('./sha256-wasm.js');
|
|
if (!b64) return wasm;
|
|
const bin = typeof Buffer !== 'undefined' ? Uint8Array.from(Buffer.from(b64, 'base64'))
|
|
: Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
|
|
const memory = new WebAssembly.Memory({ initial: (DATA + CHUNK) / 65536, maximum: (DATA + CHUNK) / 65536 });
|
|
const inst = new WebAssembly.Instance(new WebAssembly.Module(bin), { env: { memory } });
|
|
const e = {
|
|
compress: inst.exports.compress,
|
|
state: new Uint32Array(memory.buffer, STATE, 8),
|
|
data: new Uint8Array(memory.buffer, DATA, CHUNK),
|
|
};
|
|
// Self-test: one padded block of "abc" must give the well-known digest.
|
|
e.state.set(IV);
|
|
e.data.fill(0, 0, 64); e.data.set([0x61, 0x62, 0x63, 0x80], 0); e.data[63] = 24;
|
|
e.compress(STATE, DATA, 1);
|
|
if (e.state[0] !== 0xba7816bf || e.state[7] !== 0xf20015ad) return wasm;
|
|
wasm = e;
|
|
} catch { wasm = null; }
|
|
return wasm;
|
|
}
|
|
|
|
function create(opts) {
|
|
const useWasm = !(opts && opts.js) && loadWasm();
|
|
const H = new Uint32Array([
|
|
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
]);
|
|
const W = new Uint32Array(64);
|
|
const block = new Uint8Array(64);
|
|
let blockLen = 0;
|
|
let total = 0; // bytes hashed so far (safe to 2^53)
|
|
let done = false;
|
|
|
|
function compress(buf, off) {
|
|
for (let i = 0; i < 16; i++) {
|
|
const j = off + i * 4;
|
|
W[i] = (buf[j] << 24) | (buf[j + 1] << 16) | (buf[j + 2] << 8) | buf[j + 3];
|
|
}
|
|
for (let i = 16; i < 64; i++) {
|
|
const w15 = W[i - 15], w2 = W[i - 2];
|
|
const s0 = ((w15 >>> 7) | (w15 << 25)) ^ ((w15 >>> 18) | (w15 << 14)) ^ (w15 >>> 3);
|
|
const s1 = ((w2 >>> 17) | (w2 << 15)) ^ ((w2 >>> 19) | (w2 << 13)) ^ (w2 >>> 10);
|
|
W[i] = (W[i - 16] + s0 + W[i - 7] + s1) | 0;
|
|
}
|
|
let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];
|
|
for (let i = 0; i < 64; i++) {
|
|
const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
|
|
const ch = (e & f) ^ (~e & g);
|
|
const t1 = (h + S1 + ch + K[i] + W[i]) | 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;
|
|
h = 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] + h) | 0;
|
|
}
|
|
|
|
// Hash n whole 64-byte blocks of buf starting at off — wasm in 1 MiB windows, else JS.
|
|
function blocks(buf, off, n) {
|
|
if (!useWasm) { for (let k = 0; k < n; k++) compress(buf, off + k * 64); return; }
|
|
const w = useWasm;
|
|
w.state.set(H);
|
|
const per = CHUNK / 64;
|
|
for (let done = 0; done < n;) {
|
|
const m = Math.min(per, n - done);
|
|
w.data.set(buf.subarray(off + done * 64, off + (done + m) * 64));
|
|
w.compress(STATE, DATA, m);
|
|
done += m;
|
|
}
|
|
H.set(w.state);
|
|
}
|
|
|
|
function update(data) {
|
|
if (done) throw new Error('sha256: update() after digest');
|
|
const u8 = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
let i = 0;
|
|
total += u8.length;
|
|
if (blockLen) {
|
|
const take = Math.min(64 - blockLen, u8.length);
|
|
block.set(u8.subarray(0, take), blockLen);
|
|
blockLen += take;
|
|
i = take;
|
|
if (blockLen === 64) { blocks(block, 0, 1); blockLen = 0; }
|
|
}
|
|
const whole = Math.floor((u8.length - i) / 64);
|
|
if (whole) { blocks(u8, i, whole); i += whole * 64; }
|
|
if (i < u8.length) { block.set(u8.subarray(i), 0); blockLen = u8.length - i; }
|
|
return api;
|
|
}
|
|
|
|
function digest() {
|
|
if (!done) {
|
|
done = true;
|
|
const bits = total * 8;
|
|
block[blockLen++] = 0x80;
|
|
if (blockLen > 56) { block.fill(0, blockLen); blocks(block, 0, 1); blockLen = 0; }
|
|
block.fill(0, blockLen, 56);
|
|
const hi = Math.floor(bits / 0x100000000), lo = bits >>> 0;
|
|
block[56] = hi >>> 24; block[57] = hi >>> 16; block[58] = hi >>> 8; block[59] = hi;
|
|
block[60] = lo >>> 24; block[61] = lo >>> 16; block[62] = lo >>> 8; block[63] = lo;
|
|
blocks(block, 0, 1);
|
|
}
|
|
const out = new Uint8Array(32);
|
|
for (let i = 0; i < 8; i++) {
|
|
out[i * 4] = H[i] >>> 24; out[i * 4 + 1] = H[i] >>> 16; out[i * 4 + 2] = H[i] >>> 8; out[i * 4 + 3] = H[i];
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function hex() {
|
|
let s = '';
|
|
for (const b of digest()) s += (b < 16 ? '0' : '') + b.toString(16);
|
|
return s;
|
|
}
|
|
|
|
const api = { update, digest, hex, get bytes() { return total; } };
|
|
return api;
|
|
}
|
|
|
|
const Sha256 = {
|
|
create,
|
|
hex: (data) => create().update(data).hex(),
|
|
// Which engine create() will use: 'wasm' or 'js'.
|
|
engine: () => (loadWasm() ? 'wasm' : 'js'),
|
|
isHex: (s) => typeof s === 'string' && /^[0-9a-f]{64}$/.test(s),
|
|
};
|
|
if (typeof module !== 'undefined' && module.exports) module.exports = Sha256;
|
|
else root.Sha256 = Sha256;
|
|
})(typeof globalThis !== 'undefined' ? globalThis : this);
|