Verify Ed25519 signatures in the browser with WebCrypto: a hands-on walkthrough
You download a dataset — a CSV, a PDF, a JSON file — and start building on it. A week later someone asks a simple question: how do you know the file wasn't altered after it was published? Usually, you don't. "Who issued
You download a dataset — a CSV, a PDF, a JSON file — and start building on it. A week later someone asks a simple question: how do you know the file wasn't altered after it was published? Usually, you don't. "Who issued this" rests on a filename and the sender's say-so, and "was it changed" rests on nothing at all.
Digital signatures turn both questions into arithmetic. I run a small API that returns Japanese company records as JSON with an Ed25519 signature attached, precisely so a receiver doesn't have to trust me: anyone can check, with a published public key, that a record came from the issuer and that not one byte changed since. The check runs entirely in the browser with the WebCrypto API — no library, no server round-trip, nothing uploaded.
This post walks through that verification step by step, with a real record and the actual code that checks it. Everything below runs in a browser console.
The signing scheme, in brief
A record looks like this (a real one, captured as-is):
{
"record_version": "1.0",
"record_type": "regbase-record/1",
"subject": { "corporate_number": "1010001000006" },
"claims": [
{
"field": "company_name",
"value": "五洋建設株式会社",
"source": "EDINET code list (listed_codes_detail.csv)",
"as_of": "2026-11-07"
},
{
"field": "listed_status",
"value": "Listed company",
"source": "EDINET code list (listed_codes_detail.csv)",
"as_of": "2026-11-07"
},
{
"field": "securities_code",
"value": "18930",
"source": "EDINET code list (listed_codes_detail.csv)",
"as_of": "2026-11-07"
},
{
"field": "edinet_code",
"value": "E00086",
"source": "EDINET code list (listed_codes_detail.csv)",
"as_of": "2026-11-07"
}
],
"issued_at": "2026-11-16T11:36:49Z",
"issuer": "RegBase T3 sandbox",
"signature": {
"algorithm": "Ed25519",
"key_id": "9f01575a05050b62",
"signature": "17tabdG5NTsxJlMbaUKUbAFLxjkeyoMckEVzk6w3hx4JaZjNOZqcxuMD0BJpFUnBZA3APPlxVcPmARz4svgLBw=="
}
}
Three things to know before the code:
-
The signed payload is the record minus its
signatureblock. Everything else — subject, claims, timestamps — is covered. - The payload is canonicalised before signing and before verifying: object keys sorted recursively, compact JSON (no whitespace), UTF-8 encoded, no trailing newline. Both sides must produce byte-identical output, or verification fails on perfectly good records. This, not the signature itself, is where implementations go wrong.
-
The
key_ididentifies the key, not the record. It is the first 8 bytes (hex) of the SHA-256 of the public key in SPKI form, so a key rotation changes the ID visibly instead of silently breaking every check.
The public key itself is published and constant for this key generation — raw Ed25519, base64:
LZJcl0wBWsorubi6uzz6J67HNZhiIhl0G/Lay+iMLK0=
Step 0: decode base64 strictly
WebCrypto works on bytes, and both the key and the signature arrive as base64 strings. A small decoder converts them — and validates the input instead of letting atob silently swallow garbage, because a signature that fails to decode should be a malformed record result, not a mysterious exception:
function b64ToBytes(b64) {
if (typeof b64 !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(b64) || b64.length % 4 === 1) {
throw new Error('bad base64');
}
var bin = atob(b64);
var out = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
The verifier also needs the inverse helper later, to confirm a signature string is canonical base64 and not just decodable:
function bytesToB64(bytes) {
var bin = '';
for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
return btoa(bin);
}
Step 1: import the public key
crypto.subtle.importKey turns the raw key bytes into a CryptoKey the verify call can use. For Ed25519 the format is 'raw', the algorithm descriptor is just { name: 'Ed25519' }, and the key only needs the 'verify' usage. The demo code caches the resulting promise so the import happens once per page, not once per record:
var PUBKEY_B64 = 'LZJcl0wBWsorubi6uzz6J67HNZhiIhl0G/Lay+iMLK0=';
var cryptoKeyPromise = null;
function getKey() {
if (!cryptoKeyPromise) {
cryptoKeyPromise = crypto.subtle.importKey(
'raw', b64ToBytes(PUBKEY_B64), { name: 'Ed25519' }, false, ['verify']);
}
return cryptoKeyPromise;
}
Two practical notes. WebCrypto is only available in secure contexts (HTTPS, or localhost), so this code belongs on a real page or a local dev server, not a file:// document. And if the browser is old enough not to expose Ed25519 through WebCrypto, importKey rejects — the verifier below catches that and reports it as its own case instead of crashing.
Step 2: rebuild the exact bytes that were signed
This is the step that decides whether everything else works. The verifier must reconstruct the payload bit-for-bit: strip the signature block, sort every object's keys (including nested objects, and objects inside arrays), serialise compactly, and encode as UTF-8:
function sortKeys(v) {
if (Array.isArray(v)) return v.map(sortKeys);
if (v && typeof v === 'object') {
var o = {};
Object.keys(v).sort().forEach(function (k) { o[k] = sortKeys(v[k]); });
return o;
}
return v;
}
function canonicalPayload(record) {
var rest = {};
Object.keys(record).forEach(function (k) { if (k !== 'signature') rest[k] = record[k]; });
return new TextEncoder().encode(JSON.stringify(sortKeys(rest)));
}
JSON.stringify on the key-sorted object gives the compact form with no spaces, and TextEncoder gives UTF-8 — matching the signing side exactly. Get any part of this wrong (forget a nested object, sort only the top level, leave a trailing newline in your own serialiser) and valid records start failing, which is a much more confusing bug than an invalid record passing.
Step 3: verify — and check the cheap things first
The crypto call itself is one line. crypto.subtle.verify takes the algorithm, the key, the signature bytes, and the payload bytes, and resolves to a boolean. One semantic detail matters for everything that follows: a bad signature is not an exception. The promise resolves to false — rejection is reserved for operational problems, like an unusable key object or an algorithm the browser doesn't implement. So "the math said no" and "the check could not run" arrive through two different channels, and a well-behaved verifier keeps them separate instead of collapsing both into "invalid":
var ok = await crypto.subtle.verify(
{ name: 'Ed25519' }, key, sigBytes, canonicalPayload(record));
But a verifier that jumps straight to this line gives useless answers: "false" for a truncated paste, "false" for a record signed by a rotated key, "false" for a record from a different scheme entirely. The production verifier therefore runs the cheap structural checks first, in a fixed order, and gives each failure its own name — the same names the API's own verifier returns:
var EXPECTED_KEY_ID = '9f01575a05050b62';
// Mirrors the API's own verifier (same checks, same order, same error names).
async function verifyRecord(record) {
var bad = { valid: false, error: 'RECORD_MALFORMED' };
if (!record || typeof record !== 'object' || Array.isArray(record)) return bad;
var required = ['record_version', 'record_type', 'subject', 'claims', 'issued_at', 'issuer', 'signature'];
for (var i = 0; i < required.length; i++) if (!(required[i] in record)) return bad;
if (typeof record.record_version !== 'string' || typeof record.record_type !== 'string') return bad;
if (!record.subject || !/^[0-9]{13}$/.test(record.subject.corporate_number)) return bad;
if (!Array.isArray(record.claims)) return bad;
for (var c = 0; c < record.claims.length; c++) {
var claim = record.claims[c];
if (!claim || typeof claim !== 'object') return bad;
if (Object.keys(claim).sort().join(',') !== 'as_of,field,source,value') return bad;
if (!['field', 'value', 'source', 'as_of'].every(function (k) { return typeof claim[k] === 'string'; })) return bad;
}
if (typeof record.issued_at !== 'string' || typeof record.issuer !== 'string') return bad;
var sig = record.signature;
if (!sig || typeof sig !== 'object') return bad;
if (!['algorithm', 'key_id', 'signature'].every(function (k) { return typeof sig[k] === 'string'; })) return bad;
var sigBytes;
try { sigBytes = b64ToBytes(sig.signature); } catch (e) { return bad; }
if (sigBytes.length !== 64 || bytesToB64(sigBytes) !== sig.signature) return bad;
if (sig.algorithm !== 'Ed25519') return { valid: false, error: 'UNSUPPORTED_ALGORITHM' };
if (sig.key_id !== EXPECTED_KEY_ID) return { valid: false, error: 'KEY_ID_MISMATCH' };
var key;
try { key = await getKey(); }
catch (e) { return { valid: false, error: 'BROWSER_UNSUPPORTED' }; }
var ok = await crypto.subtle.verify({ name: 'Ed25519' }, key, sigBytes, canonicalPayload(record));
if (!ok) return { valid: false, error: 'SIGNATURE_INVALID' };
return { valid: true, key_id: sig.key_id, corporate_number: record.subject.corporate_number };
}
Handling the result is then a matter of switching on a small, closed set of outcomes instead of interpreting a bare boolean:
// In a browser console, with the record above pasted as `record`:
console.log(await verifyRecord(record));
// → { valid: true, key_id: '9f01575a05050b62', corporate_number: '1010001000006' }
Failure cases, and what each one looks like
-
RECORD_MALFORMED— the input isn't a complete record: invalid JSON, a missing top-level field, a claim with the wrong shape, a signature that isn't 64 bytes once decoded. This is the "you pasted half a file" case, and catching it before the crypto keeps it separate from genuine forgery. -
UNSUPPORTED_ALGORITHM— the signature block names something other than Ed25519. The verifier refuses rather than guessing, so a future scheme change is explicit, never silent. -
KEY_ID_MISMATCH— the record was signed under a different key than the one this verifier pins. After a key rotation this is the expected result for old records, and it tells you to fetch the right key instead of declaring the record fake. -
SIGNATURE_INVALID— everything is well-formed, the key is the right one, and the math still says no: at least one byte of the payload differs from what was signed. Try it yourself — take the sample record, change the last character of the first claim's value (the demo this code comes from has a Tamper button that does exactly that), and re-run. A single character is enough. -
BROWSER_UNSUPPORTED—importKeyitself failed: the browser doesn't expose Ed25519 through WebCrypto. Current Chrome, Edge, Firefox, and Safari handle it; anything older lands here rather than throwing an unhandled rejection.
Notice the ordering: the cryptographic verdict is the last thing computed, and it is the only one that means "this record was altered or never issued". Every other outcome means "this check could not be run as intended", which is a different operational problem with a different fix.
What a valid signature does not prove
It proves the record was issued by whoever holds the signing key, and that it is byte-identical to what they issued. It does not prove the claims inside are true. That gap is deliberate in the record design: every claim carries its own source dataset and as_of date, so the receiver can judge the evidence instead of extending the signature's authority to facts it never covered. Verification answers "who issued this, when, and was it touched" — the rest stays with the reader.
Closing notes
If you take one thing from this walkthrough, take the canonicalisation. Signing is a few lines with any modern library; deciding exactly which bytes get signed, writing that rule down, and implementing it identically on both sides is the work. WebCrypto makes the browser a perfectly good verifier — no extension, no library, no server — as long as the byte-building is deterministic.
The MDN references for the two calls used here: SubtleCrypto.importKey() and SubtleCrypto.verify().
Disclosure: this article was drafted with AI assistance and reviewed and tested by the author.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.