refactor: hash a file in slices in one module

MD5 and CRC32 take the file piece by piece, so a large file keeps the page responsive. The lookup and the wanted page read the same code, checked against hashlib and zlib.
This commit is contained in:
Abdessamad Derraz committed 2026-11-13 10:45:12 +01:00
1 parent b18e478db0
commit d685451f44
3 files changed
+191 -86

No files matched your search

+64 -13
View File
@@ -43,6 +43,7 @@ WEBSITE = REPO_ROOT / "website"
DIST = WEBSITE / "dist"
COMPONENTS = WEBSITE / "src" / "components"
SITE_TS = WEBSITE / "src" / "scripts" / "site.ts"
HASHES_TS = WEBSITE / "src" / "scripts" / "hashes.ts"
CONFIG = WEBSITE / "astro.config.mjs"
PLUGIN = WEBSITE / "src" / "plugins" / "rehype-stack-tables.mjs"
@@ -497,26 +498,76 @@ class HashAFileHere(unittest.TestCase):
source = _read(SITE_TS)
self.assertIn("input.type = 'file';", source)
self.assertIn("It is hashed on this device. Nothing is uploaded.", source)
self.assertIn("crypto.subtle.digest(name, buffer)", source)
self.assertIn("['SHA-1', 'SHA-256']", source)
self.assertIn("import { type FileHashes, hashFile } from './hashes.ts';", source)
self.assertIn("lookUp(status, result, [found.sha1, found.md5, found.crc32, found.sha256])", source)
hashing = _read(HASHES_TS)
self.assertIn("crypto.subtle.digest(name, buffer)", hashing)
self.assertIn("['SHA-1', 'SHA-256']", hashing)
def test_md5_and_crc32_match_python(self):
source = _read(SITE_TS)
block = source[source.index("// Hashing a file on this device"):source.index("type FileHashes")]
sizes = [0, 1, 55, 56, 63, 64, 65, 119, 120, 128, 1000, 70_001]
out = _node_module(block + (
f"console.log(JSON.stringify({json.dumps(sizes)}.map((n) => {{"
"const bytes = new Uint8Array(n);"
"for (let i = 0; i < n; i += 1) bytes[i] = (i * 31 + 7) & 0xff;"
"return [md5(bytes), crc32(bytes)]; })));"
class FileHashesMatchPython(unittest.TestCase):
"""MD5 and CRC32 are written here, Web Crypto having neither: each is
checked against hashlib and zlib, whole and fed in uneven slices, and
hashFile's four values against a file read in 4 MiB slices."""
SIZES = [0, 1, 55, 56, 63, 64, 65, 119, 120, 128, 1000, 70_001]
@staticmethod
def _bytes(size: int) -> bytes:
return bytes((i * 31 + 7) & 0xFF for i in range(size))
def _run(self, body: str) -> list:
return json.loads(_node_module(
f"import {{ Crc32, Md5, crc32, hashFile, md5 }} from {json.dumps(HASHES_TS.as_uri())};"
"const fill = (n) => { const b = new Uint8Array(n);"
" for (let i = 0; i < n; i += 1) b[i] = (i * 31 + 7) & 0xff; return b; };" + body
))
for size, (md5, crc) in zip(sizes, json.loads(out)):
data = bytes((i * 31 + 7) & 0xFF for i in range(size))
def test_md5_and_crc32_whole(self):
out = self._run(
f"console.log(JSON.stringify({json.dumps(self.SIZES)}.map((n) => "
"{ const bytes = fill(n); return [md5(bytes), crc32(bytes)]; })));"
)
for size, (md5, crc) in zip(self.SIZES, out):
data = self._bytes(size)
with self.subTest(size=size):
self.assertEqual(md5, hashlib.md5(data).hexdigest())
self.assertEqual(crc, f"{zlib.crc32(data):08x}")
def test_md5_and_crc32_in_slices(self):
"""A slice ending inside a 64-byte block carries it to the next."""
size, steps = 200_003, [1, 63, 64, 65, 3, 1000, 7, 100_000]
out = self._run(
f"const bytes = fill({size}); const steps = {json.dumps(steps)};"
"const m = new Md5(); const c = new Crc32();"
"for (let at = 0, k = 0; at < bytes.length; k += 1) {"
" const piece = bytes.subarray(at, at + steps[k % steps.length]);"
" m.update(piece); c.update(piece); at += piece.length; }"
"console.log(JSON.stringify([m.digest(), c.digest()]));"
)
data = self._bytes(size)
self.assertEqual(out, [hashlib.md5(data).hexdigest(), f"{zlib.crc32(data):08x}"])
def test_hash_file_reads_slices_and_reports_progress(self):
size = 9 * 1024 * 1024 + 17
out = self._run(
f"const shares = []; const found = await hashFile(new Blob([fill({size})]),"
" (share) => shares.push(share));"
"console.log(JSON.stringify([found, shares.length, shares.at(-1),"
" shares.every((v, i) => i === 0 || v >= shares[i - 1])]));"
)
data = self._bytes(size)
found, steps, last, rising = out
self.assertEqual(found, {
"sha1": hashlib.sha1(data).hexdigest(),
"md5": hashlib.md5(data).hexdigest(),
"crc32": f"{zlib.crc32(data):08x}",
"sha256": hashlib.sha256(data).hexdigest(),
})
self.assertGreaterEqual(steps, 3)
self.assertEqual(last, 1)
self.assertTrue(rising)
class SearchFoldsPagesUnderAHash(unittest.TestCase):
"""Under "Look up this hash" came 14 unrelated pages: Magnavox for
+125
View File
@@ -0,0 +1,125 @@
// Hashing a file on this device: SHA1 and SHA256 by Web Crypto, MD5 and
// CRC32 here, since Web Crypto has neither. The bytes never leave the page.
// MD5 and CRC32 take the file piece by piece, so a large file is read in
// slices and the page keeps answering between them.
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n += 1) {
let c = n;
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
export const hexBytes = (bytes: Uint8Array) => [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
export class Crc32 {
crc = 0xffffffff;
update(bytes: Uint8Array): this {
let crc = this.crc;
for (let i = 0; i < bytes.length; i += 1) crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
this.crc = crc;
return this;
}
digest(): string {
return ((this.crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0');
}
}
const MD5_SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
const MD5_TABLE = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
// RFC 1321. Whole 64-byte blocks are read in place from each slice; only a
// block split between two slices is copied.
export class Md5 {
state = new Int32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]);
words = new Int32Array(16);
pending = new Uint8Array(64);
pendingLength = 0;
length = 0;
block(view: DataView, offset: number) {
const words = this.words;
const state = this.state;
for (let i = 0; i < 16; i += 1) words[i] = view.getInt32(offset + i * 4, true);
let [a, b, c, d] = state;
for (let i = 0; i < 64; i += 1) {
const round = i >> 4;
const f = round === 0 ? (b & c) | (~b & d) : round === 1 ? (d & b) | (~d & c) : round === 2 ? b ^ c ^ d : c ^ (b | ~d);
const g = round === 0 ? i : round === 1 ? (5 * i + 1) % 16 : round === 2 ? (3 * i + 5) % 16 : (7 * i) % 16;
const shift = MD5_SHIFTS[round * 4 + (i % 4)];
const sum = (a + f + MD5_TABLE[i] + words[g]) | 0;
a = d;
d = c;
c = b;
b = (b + ((sum << shift) | (sum >>> (32 - shift)))) | 0;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
}
update(bytes: Uint8Array): this {
this.length += bytes.length;
let start = 0;
if (this.pendingLength) {
start = Math.min(64 - this.pendingLength, bytes.length);
this.pending.set(bytes.subarray(0, start), this.pendingLength);
this.pendingLength += start;
if (this.pendingLength < 64) return this;
this.block(new DataView(this.pending.buffer), 0);
this.pendingLength = 0;
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const whole = start + ((bytes.length - start) - ((bytes.length - start) % 64));
for (let offset = start; offset < whole; offset += 64) this.block(view, offset);
this.pending.set(bytes.subarray(whole));
this.pendingLength = bytes.length - whole;
return this;
}
digest(): string {
const tail = new Uint8Array(this.pendingLength < 56 ? 64 : 128);
tail.set(this.pending.subarray(0, this.pendingLength));
tail[this.pendingLength] = 0x80;
const view = new DataView(tail.buffer);
const bits = this.length * 8;
view.setUint32(tail.length - 8, bits >>> 0, true);
view.setUint32(tail.length - 4, Math.floor(bits / 2 ** 32), true);
for (let offset = 0; offset < tail.length; offset += 64) this.block(view, offset);
return hexBytes(new Uint8Array(this.state.buffer));
}
}
export const md5 = (bytes: Uint8Array) => new Md5().update(bytes).digest();
export const crc32 = (bytes: Uint8Array) => new Crc32().update(bytes).digest();
export type FileHashes = { sha1: string; md5: string; crc32: string; sha256: string };
const SLICE = 4 * 1024 * 1024;
// The four hashes of a file. MD5 and CRC32 read it slice by slice, each
// slice awaited so the page stays responsive; *progress* gets the share
// read so far, from 0 to 1. SHA1 and SHA256 then hash it whole in Web
// Crypto, which works off the page's own thread.
export const hashFile = async (file: Blob, progress?: (share: number) => void): Promise<FileHashes> => {
const md5State = new Md5();
const crcState = new Crc32();
for (let offset = 0; offset < file.size; offset += SLICE) {
const bytes = new Uint8Array(await file.slice(offset, offset + SLICE).arrayBuffer());
md5State.update(bytes);
crcState.update(bytes);
progress?.(Math.min(1, (offset + bytes.length) / file.size));
}
const buffer = await file.arrayBuffer();
const [sha1, sha256] = await Promise.all(
['SHA-1', 'SHA-256'].map(async (name) => hexBytes(new Uint8Array(await crypto.subtle.digest(name, buffer)))),
);
progress?.(1);
return { sha1, md5: md5State.digest(), crc32: crcState.digest(), sha256 };
};
+2 -73
View File
@@ -7,6 +7,8 @@
// Which tables stack on a phone is decided when the page is built
// (src/plugins/rehype-stack-tables.mjs), so the layout is right on first paint.
import { type FileHashes, hashFile } from './hashes.ts';
const HASH_LENGTHS: Record<number, string> = { 8: 'CRC32', 32: 'MD5', 40: 'SHA1', 64: 'SHA256' };
// One line of api/v1/lookup/. `system_name` is read when a record carries it.
// `algorithm` is the hash the value was found under, `declared` the hash
@@ -263,79 +265,6 @@ const breakPaths = () => {
});
};
// Hashing a file on this device: SHA1 and SHA256 by Web Crypto, MD5 and
// CRC32 here, since Web Crypto has neither. The bytes never leave the page.
const CRC_TABLE = (() => {
const table = new Uint32Array(256);
for (let n = 0; n < 256; n += 1) {
let c = n;
for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
table[n] = c >>> 0;
}
return table;
})();
const crc32 = (bytes: Uint8Array): string => {
let crc = 0xffffffff;
for (let i = 0; i < bytes.length; i += 1) crc = CRC_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
return ((crc ^ 0xffffffff) >>> 0).toString(16).padStart(8, '0');
};
const MD5_SHIFTS = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
const MD5_TABLE = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32) >>> 0);
const hexBytes = (bytes: Uint8Array) => [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');
// RFC 1321, block by block over the file's own buffer: no padded copy of a
// 500 MB file.
const md5 = (bytes: Uint8Array): string => {
const state = new Int32Array([0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]);
const words = new Int32Array(16);
const block = (view: DataView, offset: number) => {
for (let i = 0; i < 16; i += 1) words[i] = view.getInt32(offset + i * 4, true);
let [a, b, c, d] = state;
for (let i = 0; i < 64; i += 1) {
const round = i >> 4;
const f = round === 0 ? (b & c) | (~b & d) : round === 1 ? (d & b) | (~d & c) : round === 2 ? b ^ c ^ d : c ^ (b | ~d);
const g = round === 0 ? i : round === 1 ? (5 * i + 1) % 16 : round === 2 ? (3 * i + 5) % 16 : (7 * i) % 16;
const shift = MD5_SHIFTS[round * 4 + (i % 4)];
const sum = (a + f + MD5_TABLE[i] + words[g]) | 0;
a = d;
d = c;
c = b;
b = (b + ((sum << shift) | (sum >>> (32 - shift)))) | 0;
}
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
};
const whole = bytes.length - (bytes.length % 64);
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
for (let offset = 0; offset < whole; offset += 64) block(view, offset);
const tail = new Uint8Array(bytes.length - whole < 56 ? 64 : 128);
tail.set(bytes.subarray(whole));
tail[bytes.length - whole] = 0x80;
const tailView = new DataView(tail.buffer);
const bits = bytes.length * 8;
tailView.setUint32(tail.length - 8, bits >>> 0, true);
tailView.setUint32(tail.length - 4, Math.floor(bits / 2 ** 32), true);
for (let offset = 0; offset < tail.length; offset += 64) block(tailView, offset);
return hexBytes(new Uint8Array(state.buffer));
};
type FileHashes = { sha1: string; md5: string; crc32: string; sha256: string };
const hashFile = async (file: Blob): Promise<FileHashes> => {
const buffer = await file.arrayBuffer();
const bytes = new Uint8Array(buffer);
const [sha1, sha256] = await Promise.all(
['SHA-1', 'SHA-256'].map(async (name) => hexBytes(new Uint8Array(await crypto.subtle.digest(name, buffer)))),
);
return { sha1, md5: md5(bytes), crc32: crc32(bytes), sha256 };
};
// files/?hash= reads one shard of the lookup, named by the first two hex
// characters of the value. ?md5=, ?crc32= and ?sha256= are read the same way.