const encoder = new TextEncoder();
const hex = bytes => [...bytes].map(b => b.toString(16).padStart(2, "0")).join("");
async function digest(note, nonce) {
const text = encoder.encode(note);
const input = new Uint8Array(nonce.length + 1 + text.length);
input.set(nonce);
input[input.length - text.length - 1] = 0;
input.set(text, nonce.length + 1);
return hex(new Uint8Array(await crypto.subtle.digest("SHA-256", input)));
}
async function seal(note) {
if (typeof note !== "string" || !note) throw new Error("A note is required");
const openingKey = crypto.getRandomValues(new Uint8Array(32));
return {
commitment: await digest(note, openingKey),
privateOpeningKey: hex(openingKey),
};
}
async function verify(note, privateKey, commitment) {
if (!/^[0-9a-f]{64}$/i.test(privateKey)) throw new Error("Invalid opening key");
const key = Uint8Array.from(
privateKey.match(/.{2}/g),
pair => parseInt(pair, 16)
);
return (await digest(note, key)) === commitment;
}
