Checking signatures with WebCrypto
Server-side JavaScript has the standard WebCrypto global, crypto. You can import a public key that was made somewhere else, such as a passkey or another service's signing key, and check a signature with it.
When to use
Use crypto.subtle.importKey and crypto.subtle.verify when a request carries something signed by a key you did not create here: a WebAuthn assertion, a signed webhook, or a token from another service. crypto is available in every JavaScript binding, including Trigger and Processor actions.
Syntax
const key = await crypto.subtle.importKey(format, keyData, algorithm, extractable, ["verify"]);
const ok = await crypto.subtle.verify(algorithm, key, signature, data);
Accepted keys
| Algorithm | algorithm argument |
Formats | What the key must be |
|---|---|---|---|
| ECDSA | {name: "ECDSA", namedCurve: "P-256"} or "P-384" |
spki, raw |
spki: SubjectPublicKeyInfo in DER. raw: an uncompressed point, 65 bytes for P-256 or 97 for P-384, starting 0x04 |
| RSASSA-PKCS1-v1_5 | {name: "RSASSA-PKCS1-v1_5", hash: "SHA-256"} (or SHA-384, SHA-512) |
spki |
SubjectPublicKeyInfo in DER. Modulus of 2048 to 8192 bits |
| RSA-PSS | {name: "RSA-PSS", hash: "SHA-256"} (or SHA-384, SHA-512) |
spki |
As for RSASSA-PKCS1-v1_5 |
| Ed25519 | "Ed25519" |
spki, raw |
spki: SubjectPublicKeyInfo in DER. raw: 32 bytes |
JWK is not accepted for these algorithms.
A public key can only have the verify usage.
Signature encoding
| Algorithm | Signature verify expects |
|---|---|
| ECDSA P-256 | 64 bytes: r then s, each 32 bytes, padded with leading zeros |
| ECDSA P-384 | 96 bytes: r then s, each 48 bytes |
| RSASSA-PKCS1-v1_5, RSA-PSS | As long as the key's modulus, for example 256 bytes for a 2048-bit key |
| Ed25519 | 64 bytes |
ECDSA signatures must be in this fixed r and s form, which is what WebCrypto defines everywhere, in browsers too. A signature in ASN.1 DER form does not verify: verify resolves false. WebAuthn authenticators and many other tools produce DER, so convert it first (see the example below).
Hash and salt length
Pagelove supports each ECDSA curve with its own hash only: SHA-256 with P-256 and SHA-384 with P-384. The WebCrypto standard allows other pairings, and some other runtimes support them, but Pagelove does not. RSA-PSS supports only a salt as long as the hash: 32 bytes for SHA-256, 48 for SHA-384 and 64 for SHA-512. ECDSA needs a hash in sign and verify, as in browsers; without one the call rejects with TypeError. (Before #1768 a missing hash meant the curve's own.) You can leave out saltLength for RSA-PSS, and a salt as long as the hash is used. A saltLength that is not a non-negative whole number, such as -1, 1.5 or the string "20", is refused with TypeError. That is stricter than a browser, which would read "20" as 20.
Examples
Check a passkey assertion
A WebAuthn assertion signs the authenticator data followed by the SHA-256 hash of the client data. Store the credential's public key when the passkey is registered: in the browser, credential.response.getPublicKey() gives it in SPKI form and credential.response.getPublicKeyAlgorithm() gives its algorithm (-7 for ES256, -257 for RS256, -8 for Ed25519).
// Convert an ASN.1 DER ECDSA signature to the r and s form verify expects.
// n is 32 for P-256 and 48 for P-384.
function derToRS(der, n) {
const out = new Uint8Array(2 * n);
let i = 2;
for (let part = 0; part < 2; part++) {
const len = der[i + 1];
let int = der.slice(i + 2, i + 2 + len);
while (int.length > n && int[0] === 0) int = int.slice(1);
// Too long to be a coordinate: not a valid signature. Return zeros,
// which never verify, rather than throw.
if (int.length > n) return new Uint8Array(2 * n);
out.set(int, part * n + (n - int.length));
i += 2 + len;
}
return out;
}
async function checkES256(spki, authenticatorData, clientDataJSON, signature) {
const key = await crypto.subtle.importKey("spki", spki,
{name: "ECDSA", namedCurve: "P-256"}, false, ["verify"]);
const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", clientDataJSON));
const data = new Uint8Array(authenticatorData.length + hash.length);
data.set(authenticatorData);
data.set(hash, authenticatorData.length);
return crypto.subtle.verify({name: "ECDSA", hash: "SHA-256"}, key, derToRS(signature, 32), data);
}
If the signature is malformed, derToRS returns bytes that do not verify, so verify resolves false rather than throwing.
A valid signature is only one part of checking an assertion. You also need to check the challenge, the origin and type in the client data, the relying party ID hash and flags in the authenticator data, and make sure each challenge is used once.
Check an RS256 signature
RSA signatures need no conversion.
const key = await crypto.subtle.importKey("spki", spki,
{name: "RSASSA-PKCS1-v1_5", hash: "SHA-256"}, false, ["verify"]);
const ok = await crypto.subtle.verify("RSASSA-PKCS1-v1_5", key, signature, data);
How long generating an RSA key takes
crypto.subtle.generateKey for RSA looks for large random primes, so the time it takes depends on the key size and on chance:
- a 2048-bit key takes well under a second
- a 4096-bit key usually takes a second or two, but sometimes several seconds
Key generation cannot be stopped part-way. On a host with no time budget, server JavaScript has 5 seconds, so an unlucky 4096-bit key can run out of time. On a host with a time budget, the budget is the limit instead. generateKey does not make RSA keys over 4096 bits: a larger modulusLength is refused with OperationError. You can still import a larger RSA public key, up to 8192 bits, made elsewhere, and use it to verify signatures.
Use 2048-bit RSA keys, or elliptic curve keys such as ECDSA P-256 or Ed25519, which are much faster to generate.
Error cases
importKey, generateKey, verify, deriveBits and deriveKey return promises. When they fail, the promise rejects with a DOMException whose name says why. When an argument has the wrong type, the promise rejects with a JavaScript TypeError instead, as in browsers, so e instanceof TypeError is true. When reading the algorithm's name or hash, a derived key's length, deriveBits's length, or a parameter of HKDF or PBKDF2 runs a getter or valueOf that throws, the promise rejects with whatever it threw. A hash is read only where the algorithm takes one, so a hash given to AES or digest is ignored, as in browsers.
| What happened | name |
|---|---|
| The key is malformed: not DER, trailing bytes, a compressed point, a point not on the curve, an Ed25519 key that is not a valid point, an SPKI for a different curve or algorithm, a key with unused bits, an RSA modulus under 2048 or over 8192 bits, an even RSA modulus, or an RSA exponent that is even or outside 3 to 2^33 - 1 | DataError |
A curve other than P-256 or P-384, JWK format, or raw format for RSA |
NotSupportedError |
A key argument that is not a key crypto.subtle made, namedCurve missing for ECDSA, hash missing for RSA or for ECDSA sign and verify, or a usage that is not a WebCrypto key usage |
TypeError |
For HKDF or PBKDF2: hash, salt, info or iterations missing, a salt or info that is not a BufferSource, or an iterations that is negative, not a number or 2^32 or more |
TypeError |
For PBKDF2: an iterations of 0. For HKDF or PBKDF2: a missing or null deriveBits length, a length that is not a multiple of 8, or work that would exceed the time budget. For HKDF: more than 255 hash blocks of output. For any method that makes a key, and for HKDF or PBKDF2 deriveBits: bytes that do not fit the memory budget (with no memory budget, more than 16 MiB in total in one JavaScript call). For generateKey: an RSA modulusLength over 4096 |
OperationError |
For HKDF or PBKDF2: a hash other than SHA-1, SHA-256, SHA-384 or SHA-512. For deriveBits or deriveKey: an algorithm they do not know, or ECDH, checked before the key's algorithm and usages |
NotSupportedError |
A usage other than verify for a public key |
SyntaxError |
verify, deriveBits or deriveKey called with a known algorithm other than the one the key was imported for |
InvalidAccessError |
An ECDSA hash that does not match the curve, or an RSA-PSS saltLength other than the hash length |
NotSupportedError |
An RSA-PSS saltLength that is not a non-negative whole number |
TypeError |
A signature that does not match, or is in the wrong form, is not an error: verify resolves false.
See also
- Trigger and Processor, where JavaScript actions run
- JavaScript in schemas
- Hashing passwords with Argon2 and bcrypt