import { createHash } from "node:crypto"; import { describe, expect, it } from "vitest"; import { Sha256 } from "./media-sha256"; const node = (data: Uint8Array) => createHash("sha256").update(data).digest("hex"); const text = (value: string) => new TextEncoder().encode(value); describe("Sha256", () => { it("matches known vectors", () => { expect(new Sha256().hex()).toBe( "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", ); expect(new Sha256().update(text("abc")).hex()).toBe( "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", ); }); it("matches node:crypto across block boundaries", () => { for (const size of [1, 55, 56, 63, 64, 65, 119, 120, 128, 1000, 4097]) { const data = new Uint8Array(size); for (let index = 0; index < size; index++) data[index] = (index * 13 + size) & 0xff; expect(new Sha256().update(data).hex()).toBe(node(data)); } }); it("gives the same digest however the input is split", () => { const data = new Uint8Array(5000); for (let index = 0; index < data.length; index++) data[index] = (index * 7) & 0xff; for (const step of [1, 3, 63, 64, 100, 4096]) { const hash = new Sha256(); for (let offset = 0; offset < data.length; offset += step) { hash.update(data.subarray(offset, offset + step)); } expect(hash.hex()).toBe(node(data)); } }); it("refuses updates after finishing", () => { const hash = new Sha256(); hash.hex(); expect(() => hash.update(text("x"))).toThrow(); expect(() => hash.hex()).toThrow(); }); });