Protocol guide
Cryptography
The sv1-c1 crypto suite and the shared rules every other document builds on, from strict base64url and Ed25519 verification to the JWS profile, label registries, AEAD, HPKE, SVF1, CPace, Argon2id and the test vectors.
Specification: 04 Cryptographic conventions
Document 04 fixes the bytes and checks around every signed or encrypted object in Sloppy Voice. It defines no endpoints or events. Other documents own the claims of their objects; 04 owns the JWS profile they follow, the Ed25519 rules that verify them, the label strings their derivations use, and the formats shared across documents (04 §1).
How much of it you need depends on what you build (04 Conformance):
- Anything that creates or verifies a JWS (servers, clients of every kind, push gateways) follows the encoding, Ed25519, JWK and JWS rules (04 §3 to §6). That includes clients of insecure accounts, which still verify IdentityStates to work out a DM's security state.
- Anything that holds secure-mode keys also follows the labelled-signature, derivation, AEAD, SVF1, CPace, Argon2id, randomness and key-handling rules (04 §7 to §14).
- Servers apply the rules they check structure against, such as the SVF1 blob-size rule (04 §10.7) and the Argon2id ranges (04 §12.2), although they never hold a content key.
The sv1-c1 suite
Protocol version 1 has exactly one crypto suite, sv1-c1, and every implementation implements all of it (04 §2.1):
| Use | Primitive |
|---|---|
| Signatures (server, identity and device signing keys) | Ed25519, pure (RFC 8032 §5.1), with strict verification |
| Diffie-Hellman | X25519, only inside MLS, CPace and HPKE |
| Encrypting one key to one device | HPKE base mode, single-shot: KEM 0x0020 DHKEM(X25519, HKDF-SHA256), KDF 0x0001 HKDF-SHA256, AEAD 0x0002 AES-256-GCM |
| Hashes | SHA-256; SHA-512 inside Ed25519, CPace and safety numbers |
| Key derivation and MAC | HKDF-SHA256, HMAC-SHA256 |
| Application AEAD | AES-256-GCM, 96-bit nonce, 128-bit tag |
| Attachments | AES-256-GCM in 64 KiB segments, SVF1 format |
| Group key agreement | MLS ciphersuite 0x0001 MLS_128_DHKEMX25519_AES128GCM_SHA256_Ed25519 |
| Media encryption | SFrame cipher suite 0x0004 AES_128_GCM_SHA256_128 |
| Password-authenticated key exchange | CPace CPACE-X25519-SHA512 |
| Password hashing | Argon2id version 0x13, m = 65,536 KiB, t = 3, p = 1 |
Nothing is negotiated. No message or field lets a peer choose another algorithm or parameter set, and a verifier rejects an object that names one with crypto.unsupported_algorithm, without falling back, because negotiation is where downgrade attacks live (04 §2.2). Objects don't carry a suite ID. Those that may change format carry their own marker instead: the JWS typ, the SVF1 magic, the Argon2idParams alg and v, the CPaceAD version, and the MLS and SFrame suites. sv1-c2 is reserved for a post-quantum hybrid suite; v1 code treats every suite other than sv1-c1 as unsupported (04 §2.3).
Account keys and transport keys. Insecure accounts hold no account keys: no identity key, device signing key (DSK), box key, vault key, recovery entropy, history, message or file key, or MLS state, and their device registrations carry no public key (04 §2.4). Every client still uses transport keys (TLS, WebRTC DTLS for relay and SFU connections, browser-managed Web Push keys, the PKCE code_verifier), which are never bound to the account or used for content and protect only the hop they were negotiated for. Generate DTLS certificates fresh for each call join, or at least for each context, and never reuse one across contexts or servers, because a reused certificate's fingerprint becomes a stable identifier of the device.
Encoding
Strict base64url
Binary values in JSON are base64url without padding. For every cryptographic field (keys, signatures, hashes, thumbprints, nonces, ciphertexts, MLS objects, salts, jti, did) the decoder must also reject (04 §3.1):
- any character outside
A–Z,a–z,0–9,-,_, including=,+,/, white space and line breaks; - a length that is 1 modulo 4;
- a non-canonical tail: at length 2 modulo 4 the last character is one of
A Q g w, at length 3 modulo 4 one ofA E I M Q U Y c g k o s w 0 4 8; - a decoded length the field doesn't allow.
Failures are crypto.malformed with reason "encoding" or "length". Non-canonical input is rejected because one byte string with two spellings lets a thumbprint or pin computed over the spelling disagree for the same key. Most base64 libraries are lenient, so you will need a wrapper:
// Strict base64url decoder for cryptographic fields (04 §3.1).
declare function malformed(reason: "encoding" | "length"): Error; // builds a crypto.malformed error
export function decodeB64url(s: string, expectedLength?: number): Uint8Array {
if (!/^[A-Za-z0-9_-]*$/.test(s) || s.length % 4 === 1) throw malformed("encoding");
const last = s[s.length - 1];
if (s.length % 4 === 2 && !"AQgw".includes(last)) throw malformed("encoding");
if (s.length % 4 === 3 && !"AEIMQUYcgkosw048".includes(last)) throw malformed("encoding");
const bin = atob(s.replace(/-/g, "+").replace(/_/g, "/"));
const bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));
if (expectedLength !== undefined && bytes.length !== expectedLength) throw malformed("length");
return bytes;
}Vector V-1: "_w" decodes to ff; "_x", "_w==" and "_" are rejected.
Lengths and binary structures
| Value | Bytes | base64url characters |
|---|---|---|
| Ed25519 public key, Ed25519 seed, X25519 public key, SHA-256 output, thumbprint, AES-256 key | 32 | 43 |
| Ed25519 signature | 64 | 86 |
| AES-GCM nonce | 12 | 16 |
SealedMessage kc, did, Argon2id salt |
16 | 22 |
Epoch key ID ekid |
8 | 11 |
jti |
16 to 64 | 22 to 86 |
An Ed25519 private key that travels (in a pairing payload or KeyBackup) is the 32-byte seed, never the 64-byte expanded form. X25519 private keys never travel (04 §3.4).
Note
§3.4 gives jti as 16 to 64 bytes; the table in 04 §13 says "16 bytes or more". Generating 16 to 64 bytes satisfies both.
Every binary structure that is signed, MACed, hashed, used as associated data or HPKE info, or fed to a KDF must be injective, so two different field lists never produce the same bytes (04 §3.2). Fields are fixed-length (big-endian integers), length-prefixed with a stated width, or ended by a byte that can't occur in them. The RFC 9420 TLS presentation language is recommended because you already carry its codec for MLS. JSON is never signed or hashed except as the exact transmitted bytes of a JWS signing input, and you never re-serialize JSON to verify it, because re-serialized JSON isn't byte-stable across libraries.
Ed25519
These rules apply to every Ed25519 operation: JWS, labelled signatures and MLS signatures (04 §4). Signing is pure Ed25519, deterministic, with no context string. Each key has exactly one purpose; a DSK is never an identity key. A signer of a long-lived object (IdentityCertificate, DeviceCertificate, DeviceRevocation, KeyRotation) should verify its own signature before publishing it, to catch fault attacks on the key that is hardest to replace (04 §4.2).
Strict verification
Reject a signature unless all seven checks hold (04 §4.3):
| # | Check | Failure |
|---|---|---|
| 1 | The public key A is 32 bytes and canonically encoded (y < 2^255 − 19; not an encoding RFC 8032 §5.1.3 rejects, including x = 0 with the sign bit set). |
crypto.invalid_key |
| 2 | A has order exactly L: not one of the eight small-order points, and [L]A is the neutral element (no mixed order). |
crypto.invalid_key |
| 3 | The signature is 64 bytes, R || S. |
crypto.bad_signature |
| 4 | R is canonically encoded and decodes to a point. |
crypto.bad_signature |
| 5 | R isn't of small order. |
crypto.bad_signature |
| 6 | S < L = 2^252 + 27742317777372353535851937790883648493. |
crypto.bad_signature |
| 7 | The cofactorless equation [S]B = R + [k]A holds, with k = SHA-512(R || A || M) mod L. |
crypto.bad_signature |
Libraries disagree on these edge cases, and a signature one server accepts and another rejects would let an attacker split the federation's view of who signed what. So:
- Don't use batch verification.
- A cofactored library (including any ZIP-215 implementation) is usable only with checks 1, 2, 4, 5 and 6 around it plus a check that
[L]Ris the neutral element. Without that, vector V-4g passes a cofactored verifier and fails a cofactorless one. - libsodium's
crypto_sign_verify_detacheddoesn't reject mixed-order public keys;crypto_core_ed25519_is_valid_pointdoes, at key acceptance. OpenSSL 3.5 accepted V-4c, V-4d, V-4f, V-4i and V-4j, all of which §4.3 rejects (04 §4.6). - A web client can't rely on
crypto.subtle.verifyalone. It applies checks 1, 2, 4, 5 and 6 itself, and may use WebCrypto for checks 3 and 7 only after a start-up self-test shows the browser accepts V-4a and rejects V-4g; otherwise it uses a bundled cofactorless implementation, such as libsodium in WebAssembly. - An MLS stack either applies these rules to MLS signatures or relies on the checks made when the key was accepted: a leaf
signature_keyequals a DSK whose DeviceCertificate passed checks 1 and 2, so the stack then needs only checks 3 to 7.
The small-order encodings are listed in 04 §4.4; comparing against that list is allowed only together with the canonical-encoding check. Run checks 1 and 2 whenever a key is accepted, so later signature checks can rely on them: a server signing key fetched from ServerMetadata or accepted through keyChain; an MLS external-sender key; an identity key when its IdentityCertificate is registered, when it arrives in an IdentityState, pairing payload or KeyBackup, and when it is pinned; a DSK when its DeviceCertificate is registered or validated. A server refuses to register a failing identity key or DSK with crypto.invalid_key (04 §4.5). The V-4 vectors are the arbiter, whatever your library documents.
Note
§4.3 item 2 lets any verifier rely on the check made when a key was accepted, while the web-client rule says a web client applies item 2 "itself". Doing the check yourself at key acceptance and caching the result per key satisfies both readings.
JWKs and thumbprints
Every Ed25519 public key in JSON is an OKP JWK (Ed25519Jwk, 04 §5.1):
{"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}An identity key or DSK JWK (ik, dsk) has exactly kty, crv and x; reject one with any other member with crypto.invalid_key. Other owners may add metadata (02 adds kid, purpose, status and others to ServerMetadata keys), which never enters a thumbprint. No JWK ever contains d or another private-key member; reject one that does with crypto.invalid_key. Inside binary structures, keys are the raw 32 bytes. An X25519 key is a JWK only in a DeviceCertificate's dbk claim; elsewhere it is the base64url of the raw bytes.
The key ID of an identity key (ikf) or a DSK (dkf) is its RFC 7638 SHA-256 thumbprint (04 §5.2):
thumbprint(A) = base64url( SHA-256( "{\"crv\":\"Ed25519\",\"kty\":\"OKP\",\"x\":\"" || base64url(A) || "\"}" ) )Compute it from the decoded key re-encoded canonically, never from the received x string. Thumbprints aren't shown to people; out-of-band verification uses safety numbers (see Secure accounts). Vector V-2: the RFC 8032 test 1 key above has thumbprint kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k.
The JWS profile
Every signed object outside MLS and SFrame, except the Web Push VAPID JWT, is a compact-serialization JWS with one profile (04 §6). JSON serializations, detached or unencoded payloads, alg: none and JWE are never used. The signing input is the ASCII of b64-header "." b64-payload exactly as transmitted, and a JWS is stored and embedded as the exact compact string, never decoded and re-encoded (04 §6.1).
Header
The protected header (JwsProtectedHeader) has exactly three members: alg ("EdDSA"), typ (a registered value, compared byte for byte) and kid (04 §6.2). Any other member, including jwk, jku, x5u, x5c, crit, b64 and zip, is crypto.header_rejected. That one rule closes the classic JOSE attacks: algorithm confusion, embedded keys, remote key URLs and ignored critical extensions. The decoded header is at most 1,024 bytes. Produce it as alg, typ, kid with no white space; accept any order.
The typ registry
Document 04 owns the registry; each owner defines its type's claims (04 §6.3).
typ |
Object | Signer class | exp |
Max lifetime | Max size (bytes) | Owner |
|---|---|---|---|---|---|---|
sv-assert+jwt |
HomeAssertion | Server | Required | 300 s | 4,096 | 06 |
sv-devproof+jwt |
DeviceProof | Device | Required | 60 s | 1,024 | 06 |
sv-s2s+jwt |
S2S request token | Server | Required | 60 s | 4,096 | 06 |
sv-relay+jwt |
RelayTicket | Server | Required | 60 s | 8,192 | 15 |
sv-push+jwt |
Push gateway request token | Server | Required | 60 s | 4,096 | 19 |
sv-idstate+jwt |
IdentityState | Server | Required | 86,400 s | 32,768 | 07 |
sv-idcert+jwt |
IdentityCertificate | Identity | Forbidden | Until reset | 2,048 | 07 |
sv-devcert+jwt |
DeviceCertificate | Identity | Forbidden | Until revoked or reset | 2,048 | 07 |
sv-devrevoke+jwt |
DeviceRevocation | Identity | Forbidden | Permanent | 1,024 | 07 |
sv-keyrot+jwt |
KeyRotation | Server | Forbidden | Permanent | 2,048 | 02 |
sv-test+jwt |
Test vectors only | Any | Optional | 300 s | 8,192 | 04 |
Check the whole compact string's size before decoding anything. An owner may lower a lifetime or size, never raise one; until the registry catches up, apply the smaller value. No production verifier expects sv-test+jwt.
kid and key selection
kid is a cross-check, not a pointer: you already know from context whose key it should be, so never use it to search a key store and never take a key from the header (04 §6.4).
- Server class.
kidis<canonical-domain>#<key-id>, and the domain must equaliss. The key comes from that domain's ServerMetadatakeys, withpurpose: "sign"and astatusthat 02 allows for verification; a relay verifying a RelayTicket may instead use the key set its hosting server configured for it. On a miss, refetch the metadata at most once per minute per domain and try again. If the key is still missing or unusable, 02's discovery.unknown_key and discovery.key_unusable apply unless the type's owner names a more specific code (04 §6.8). See Discovery. - Identity class.
kidis theikfof the identity key the context expects; a mismatch is crypto.unknown_key. - Device class.
kidis thedkfof thedskin the DeviceCertificate the context expects; a mismatch iscrypto.unknown_key.
Payload and time claims
The payload is I-JSON, at most 8 levels deep (04 §6.5). Reject duplicate member names, invalid UTF-8 and lone surrogates (crypto.malformed, json); JSON.parse silently keeps the last duplicate, and two parsers resolving duplicates differently would see two objects behind one signature. Unknown claims are ignored. An aud is a single string; an array is crypto.invalid_claims (array).
Time claims are integers with one 60-second skew allowance, applied exactly here (04 §6.6):
| Claim | Valid only if | Failure |
|---|---|---|
iat (required, 0 to 2^53 − 1) |
iat ≤ now + 60 |
crypto.not_yet_valid |
exp (as the registry says; exp − iat within the lifetime) |
now < exp + 60 |
crypto.expired |
nbf (only on types whose owner defines it) |
nbf ≤ now + 60 |
crypto.not_yet_valid |
Structural problems (missing, not an integer, out of order, too long-lived) are crypto.invalid_claims. An nbf on a type that doesn't define it is crypto.invalid_claims (forbidden), because generic JWT libraries enforce nbf whenever it appears and ignoring it in some verifiers would split them.
The server is your clock source. Estimate an offset per server from the HTTP Date header and the envelope ts, and sign with corrected time: the audience server's offset for a DeviceProof, your home server's for certificates and revocations. When you check iat, exp or nbf yourself (on an IdentityState, for example), use your clock corrected by the offset to your home server, not the raw device clock. On crypto.not_yet_valid, or an owner code that reports the same failure, correct the offset, sign again and retry once. Never show the user a clock error; a failure that persists after that retry is reported as a connection problem.
Verifying
To sign, build the payload with iat, the header {"alg":"EdDSA","typ":T,"kid":kid}, encode both, sign the ASCII input and check the size (04 §6.7). To verify, run all twelve checks of 04 §6.8:
| Step | Check | Failure |
|---|---|---|
| 1 | Within T's maximum size |
crypto.malformed (size) |
| 2 | Three non-empty parts; the third is 86 characters | crypto.malformed (structure) |
| 3 | Canonical base64url | crypto.malformed (encoding) |
| 4 | Header ≤ 1,024 bytes, exactly alg, typ, kid |
crypto.malformed or crypto.header_rejected |
| 5 | alg is "EdDSA" |
crypto.unsupported_algorithm |
| 6 | typ equals T |
crypto.wrong_type |
| 7 | kid has the signer class's form |
crypto.header_rejected |
| 8 | Payload is I-JSON, no duplicates, ≤ 8 levels | crypto.malformed (json, depth) |
| 9 | Key selected and passes Ed25519 checks 1 and 2 | crypto.unknown_key, crypto.invalid_key |
| 10 | Signature verifies strictly | crypto.bad_signature |
| 11 | Time claims pass | crypto.invalid_claims, crypto.expired, crypto.not_yet_valid |
| 12 | Owner's checks (audience, jti replay, addresses, revocation) |
Owner's codes |
Any order is fine, but never accept unless every step passes, and never act on a claim before step 10 except to pick the key. Owners may substitute codes but never skip a check: 06 answers every HomeAssertion failure with 401 federation.assertion_invalid. When the failing JWS is the request's credential (an sv-s2s+jwt or sv-push+jwt in Authorization, or the HomeAssertion or DeviceProof in session creation), every crypto.* code is sent as 401 (04 §6.9); see Federation.
Self-certifying objects. An IdentityCertificate is signed by the key it contains, which proves only possession (04 §6.10). Read ik, require kid = thumbprint(ik), check ik, verify with it, then anchor ik independently through a fresh IdentityState, a HomeAssertion's ikf or the user's pin. Trusting sub without that would let anyone mint an identity for any address.
Example
Vector V-3, signed with K1 (RFC 8032 test 1) (04 §6.11):
{"alg":"EdDSA","typ":"sv-test+jwt","kid":"kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k"}
{"iss":"a.com","sub":"alice@a.com","iat":1764872400,"exp":1764872460,"jti":"Kc1o2Q8bTzR3fLw9yH0aVg"}eyJhbGciOiJFZERTQSIsInR5cCI6InN2LXRlc3Qrand0Iiwia2lkIjoia1ByS19xbXhWV2FZVkE5d3dCRjZJdW8zdlZ6ejdUeEhDVHdYQnlnclM0ayJ9.eyJpc3MiOiJhLmNvbSIsInN1YiI6ImFsaWNlQGEuY29tIiwiaWF0IjoxNzY0ODcyNDAwLCJleHAiOjE3NjQ4NzI0NjAsImp0aSI6IktjMW8yUThiVHpSM2ZMdzl5SDBhVmcifQ.vshhA3eVTv2eXuwJOC4qjEREaJY-WmLoCbPsHkX8rq4Z07lMkPXNmGvvlE-GCMkgteOCD9_KGX7dTfTJ_z-5AwIt is accepted at now = 1764872519 (exp + 59) and 1764872340 (iat = now + 60), and rejected with crypto.expired at 1764872520 and crypto.not_yet_valid at 1764872339. Cases 3d to 3o in 04 §16.3 cover the time boundaries and the rejections: a wrong typ, alg: none, an embedded jwk, a duplicate sub, a non-canonical signature character, an oversized header, an oversized JWS, an undefined nbf and an array aud. Most come with their compact form; the two oversized cases are given by construction and SHA-256.
Labelled signatures
Secure contexts only
The sections from here to Argon2id cover secure-mode keys and the structures servers check for them. Insecure contexts don't use labelled signatures, HPKE, SVF1, CPace or Argon2id. Two derivation strings are the exception: every client computes a 1:1 DM's context ID with sv1 dm, and a home server computes push collapse keys with sv1 push collapse.
A DSK signature made outside JWS and MLS signs these bytes (04 §7.1):
"sv1 sig" || 0x00 || label || 0x00 || contentThe label is a registered ASCII string of 1 to 32 lowercase letters, digits and hyphens. content is binary, never JSON, and its owner must make it injective, start it with a uint8 version, include every protected field (the ciphertext or its hash where encrypted data is covered), and bind it to its context, object ID and epoch or scope so it can't be moved (04 §7.2). In JSON the signature is 86 base64url characters. Only DSKs make labelled signatures; identity and server keys never do.
Registered labels (04 §7.3):
sealed: a SealedMessage's header fields and ciphertext (14);history-share: a HistoryShare (14);media-attest: a MediaAttestation (18);vault-box-keyandvault-generation: box key bindings and vault key generations (08);test: test vectors only;history-link: retired, never signed, accepted or reused.
A DSK's three signing contexts can't collide because their first bytes differ: a JWS signing input starts with e, I, C or D, a labelled-signature input with s, and an MLS SignContent with a byte from 0x08 to 0x3F (04 §7.4).
Vector V-5 signs UTF-8 Sloppy Voice test content with label test; the signed bytes are 73763120736967007465737400536c6f70707920566f696365207465737420636f6e74656e74.
Derivation labels
Every HKDF info, HMAC message, hash separator and HPKE info starts with a registered label matching "sv1 " word *( " " word ), at most 32 characters (04 §8.3). Each label is used with one primitive. The input is label alone, or label || 0x00 || context with an injective context; the 0x00 keeps prefix labels such as sv1 vault and sv1 vault id apart. Two exceptions come from 00: sv1 msg is "sv1 msg" || mid with no separator, and sv1 dm puts 0x0A between the two addresses.
A uniformly random key of at least 32 bytes (an MLS exporter output, a CSPRNG key, the Argon2id output, the CPace ISK) may be used directly as the PRK of HKDF-Expand; any other secret goes through HKDF-Extract first. Outputs are at most 64 bytes, and MACs are truncated only where the registry says, never below 16 bytes (04 §8.1, §8.2).
The HKDF and HMAC labels (04 §8.4):
| Label | Primitive | Input key | Output | Owner |
|---|---|---|---|---|
sv1 ekid |
HKDF-Expand | K_hist(e) |
8 bytes, epoch key ID | 14 |
sv1 msg |
HKDF-Expand | K_hist(e) |
32 bytes, K_msg |
14 |
sv1 kc |
HMAC | K_msg |
Truncated to 16, key commitment kc |
14 |
sv1 vault |
HKDF-Expand | K_vault |
32 bytes (8 for a key check value) | 08 |
sv1 vault id |
HMAC | K_vid |
Truncated to 16, vault record IDs | 08 |
sv1 backup |
HKDF-Expand | Argon2id output | 32 bytes, KeyBackup key | 08 |
sv1 pair |
HKDF-Expand | CPace ISK | 32 bytes, pairing payload and ack keys | 08 |
sv1 file key |
HKDF-Expand | K_file |
32 bytes, SVF1 K_enc |
04 |
sv1 file kc |
HKDF-Expand | K_file |
32 bytes, SVF1 commitment | 04 |
sv1 cpace kc |
HKDF-Expand | CPace ISK | 64 bytes, K_ca || K_cb |
04 |
sv1 push collapse |
HMAC | K_coll |
Truncated to 16, push collapse keys | 19 |
sv1 link and sv1 anchor are retired and never reused. The other strings are sv1 dm (SHA-256, the 1:1 DM context ID), sv1 upgrade plan (SHA-256, 09), sv1 vault grant and sv1 history-share (HPKE info), sv1 pair ci, sv1 init and sv1 resp (CPace), and sv1 safety (safety numbers) (04 §8.5). The MLS exporter may be called only with sv1 history (32 bytes, K_hist) and SFrame 1.0 Base Key (16 bytes) (04 §8.6). How those keys are used is on MLS and sealed messages and Media.
Vector V-6: with K_hist = 000102…1f and mid 01938f30-1b2c-7d4e-8f90-a1b2c3d4e5f6, ekid is 6055c06d62559306 and kc is 5a20ed32edbb23247c0b85ebfb45f493; the DM context for alice@a.com and dan@d.com is dm:KBXfagPoLlQyKu3QOiLfgw.
A document that needs a new label picks a name that matches the grammar and doesn't equal, or start with, a registered label followed by 0x00 (nothing may start with sv1 msg), defines its input layout in a "Registry additions" subsection and publishes vectors for it; the next revision of 04 registers it (04 §8.7).
AES-256-GCM
All application encryption is AES-256-GCM with a 32-byte key, a 12-byte nonce and a 16-byte tag; a ciphertext field holds the ciphertext followed by the tag (04 §9.1). Every encryption takes a fresh random nonce, except SVF1 (prefix and counter), SFrame and HPKE. Elsewhere a nonce is never a counter, timestamp or message ID (04 §9.2).
Usage bounds per key (04 §9.3):
| Key | Maximum use |
|---|---|
K_msg, K_share, an HPKE context |
One encryption |
SVF1 K_enc |
One blob, at most 2^32 segments |
| Pairing payload and ack keys | 64 encryptions |
| KeyBackup key, vault record keys | 2^32 encryptions |
| Any other AES-256-GCM key with random nonces | 2^32 encryptions, each at most 2^36 − 32 bytes |
A document that adds an AES-256-GCM key states its bound in its own text.
Associated data is deterministic bytes (never re-serialized JSON), includes every cleartext field the recipient acts on, binds the ciphertext to its place (kind, context, object ID, epoch or generation) so a server can't move it, and isn't empty (04 §9.4). Two exceptions: a fresh single-object key delivered inside a place-bound object (the SVF1 K_enc), and HPKE, whose info carries the binding.
Key commitment. AES-GCM isn't key-committing, so every ciphertext a report can reveal carries a commitment: SealedMessage kc and the SVF1 header (04 §9.5). Every decrypting party checks it in constant time before decrypting and treats a mismatch as a failure. If recipients skipped the check, a sender could attach a wrong commitment to abusive content that everyone sees but no report can verify. See Roles and moderation.
Retries (04 §9.6). Store a complete SealedMessage before the first send and resend those exact bytes within the same (generation, epoch); never encrypt twice under one (generation, epoch, mid). If the server requires a newer epoch, re-seal the same content and mid under the new K_msg with a fresh nonce, and store the new bytes before sending. If the bytes are lost in the same epoch, create the message again with a new mid. A retried upload resends the same blob; if it is lost, use a new K_file.
A failed decryption releases no plaintext, and a device never tells a remote party why it failed; locally it records crypto.decrypt_failed (04 §9.7).
HPKE grants
HPKE encrypts one key to one device's X25519 box key, and nothing else: a vault key in a VaultKeyGrant, or a HistoryShare's K_share (04 §9.8).
- Base mode, KEM
0x0020, KDF0x0001, AEAD0x0002, single-shot (SealBase/OpenBase) with a fresh ephemeral key; no exporter. infois"sv1 vault grant" || 0x00 || context(08) or"sv1 history-share" || 0x00 || mid16(shareId) || did16(did)(14). The AAD is empty.encis 32 bytes; the ciphertext is the plaintext length plus 16. A failure to open iscrypto.decrypt_failed(tag).
Check the recipient's box key before encrypting, so the server can't substitute its own: verify its vault-box-key signature for a VaultKeyGrant, or check that it equals the dbk of the DeviceCertificate in the recipient's MLS leaf for a HistoryShare. Vector V-12 gives a complete grant. The vault flows are on Secure accounts.
Attachment encryption (SVF1)
In a secure context every attachment, thumbnail and preview blob is encrypted with SVF1 before upload; in insecure contexts attachments are plaintext and unpadded (04 §10.1). SVF1 seals 64 KiB segments separately, with a nonce carrying a counter and a final-segment flag, so you can encrypt while uploading, decrypt while downloading, seek with range requests, and detect truncation and appending. The input is the raw file; SVF1 does its own framing and padding.
Keys. Generate a fresh 32-byte K_file for every blob, including a separate one for each thumbnail, and never reuse it, not even to re-upload the same file (04 §10.2):
K_enc = HKDF-Expand(K_file, "sv1 file key", 32)
commitment = HKDF-Expand(K_file, "sv1 file kc", 32)K_file travels only inside the SealedMessage content. Because it doesn't depend on the message, start encrypting and uploading as soon as the user picks a file, with no separate "encrypting" step in the interface (04 §10.8).
Padding. The plaintext is framed as u64(len(file)) || file and zero-padded to a bucket, so the server learns only an approximate size (04 §10.3). Buckets start at 4 KiB, are powers of two up to 64 KiB, and then have 8 buckets per doubling (under 12.5 % overhead):
// pad() and the blob size from 04 §10.3 and §10.4.
function pad(n: number): number {
if (n <= 4096) return 4096;
let p = 4096;
while (p < n) p *= 2; // smallest power of two >= n
if (n <= 65536) return p;
const step = p / 16; // 2^(k-3), where 2^k < n <= 2^(k+1) = p
return Math.ceil(n / step) * step;
}
const blobSize = (fileSize: number) => {
const P = pad(fileSize + 8);
return 43 + P + 16 * Math.ceil(P / 65536);
};| File size (bytes) | Bucket P |
Segments | Blob size (bytes) |
|---|---|---|---|
| 0 to 4,088 | 4,096 | 1 | 4,155 |
| 4,089 | 8,192 | 1 | 8,251 |
| 100,000 | 106,496 | 2 | 106,571 |
| 1,000,000 | 1,048,576 | 16 | 1,048,875 |
| 26,214,400 (25 MiB) | 27,262,976 | 416 | 27,269,675 |
Blob format (SVF1Header, 04 §10.4):
struct {
opaque magic[4]; // "SVF1" = 0x53 0x56 0x46 0x31
opaque nonce_prefix[7]; // random, per blob
opaque commitment[32]; // HKDF-Expand(K_file, "sv1 file kc", 32)
} SVF1Header; // 43 bytes
blob = SVF1Header || C_0 || C_1 || … || C_(n−1)
C_i = AEAD-Encrypt(K_enc, nonce_prefix || u32(i) || u8(f), SVF1Header, segment_i)f is 1 for the last segment only. Every plaintext segment is 65,536 bytes except possibly the last (4,096 to 65,536). Segment i starts at byte 43 + 65552·i.
Decryption, given the blob length B (04 §10.6); each failure is crypto.decrypt_failed with the reason shown:
B ≥ 4155and the magic isSVF1(format).- With
n = ceil((B − 43) / 65552), the last segment ciphertext is at least 4,112 bytes (format). - The commitment matches in constant time, before anything is decrypted (
commitment). - Every segment decrypts with
f = 1only on the last (tag). A truncated blob fails here. - The
sizeprefix givespad(size + 8) = B − 43 − 16·n(padding). - Output
sizebytes; all padding bytes are zero (padding).
You may stream each segment to an in-app player once its tag verifies. You must not present a saved file as complete, or hand it to another app, until every segment verifies and the output matches the signed size and sha256 of its AttachmentRef; write to a temporary location first. That hash check matters because SVF1 authenticates the blob only to holders of K_file, which includes every member who can read the message (04 §18 item 9). When streamed playback reaches the end, run the same size and sha256 check; on a mismatch stop playback, discard what you decrypted and treat the attachment as failed. A mismatch is content_hash. Failures show the generic attachment failure, never a security warning, and partial content is never shown as the file.
Server checks (04 §10.7). A server can't decrypt SVF1 but should check the structure at upload: B ≥ 4155, the SVF1 magic, a last segment of at least 4,112 bytes, and pad(P) = P. It accepts blobs up to svf1Size(maxAttachmentBytes), which is 27,269,675 bytes for the default 25 MiB, stores them unchanged and supports range requests. The upload flow is on Messaging.
Note
A wrong SVF1 magic has three codes in 04: §15.1 lists it under crypto.unsupported_algorithm, §10.7 has servers answer crypto.malformed (structure), and a decrypting client records crypto.decrypt_failed (format). For uploads, §10.7 and document 11 use crypto.malformed.
Vector V-9 uses K_file = 404142…5f and nonce_prefix = a0a1a2a3a4a5a6, giving K_enc = fbcc8179…b8021858, and covers a 20-byte file, a 100,000-byte file, truncation, a wrong key and appended data.
CPace pairing
Pairing moves keys between two devices of one account over messages the home server relays, and CPace lets a 6-digit code resist that server (04 §11). The session and message bodies belong to 08 and are on Secure accounts; 04 defines every CPace byte.
The profile is pinned to draft-irtf-cfrg-cpace-13, suite CPACE-X25519-SHA512, DSI "CPace255", initiator-responder mode, with mandatory key confirmation. Reproduce the draft's Appendix B.1 vectors first (04 §11.1).
The initiator is the device on which the user enters the secret (scans the QR code or types the code), because only it knows which secret was used. The responder displays them (04 §11.2).
| Input | Value |
|---|---|
prs_kind |
1 for the QR code (08 cred "qr"), 2 for the typed code ("code") |
PRS |
The 16-byte QR secret, or the ASCII of the 6 digits with leading zeros |
CI |
lv_cat("sv1 pair ci", u8(prs_kind), pairing_id, address) |
sid |
pairing_id, the 16-byte session UUIDv7 |
ADa, ADb |
CPaceAD { "sv1 init" or "sv1 resp", 1, did }, 26 bytes: 0x08 || role || 0x01 || did |
Each device checks the peer's role, version and did against the session and aborts on a mismatch, so a relaying server can't splice sessions or redirect a run to a third device (04 §11.3).
- The initiator computes
g = calculate_generator(H, PRS, CI, sid)andYa, and sendscpace_a(cred,ya,ad). - The responder checks
ADa, computesYbandK, aborts ifKis 32 zero bytes, computesISK, thenK_ca || K_cb = HKDF-Expand(ISK, "sv1 cpace kc", 64)andtb = HMAC(K_cb, transcript), and sendscpace_b(yb,ad,tb). - The initiator checks
ADb, derives the same keys and verifiestbin constant time. On a mismatch it sends only 08'sabort; otherwise it sendsconfirm_awithta = HMAC(K_ca, transcript). - The responder verifies
ta.
Neither device derives the sv1 pair keys or sends or accepts the payload until its run is confirmed (04 §11.5). Each erases the scalars, K and the confirmation keys once its run is confirmed or aborted, and erases ISK once the pairing payload and ack keys are derived (04 §11.6). Vector V-11b as 08 carries it:
{ "cred": "code", "ya": "rgaQeP8rXRUgsKHH9umgpxZvuEdpJ4iV9okf6rIJx1w", "ad": "CHN2MSBpbml0Aatm0vcVYN5tMiaUHtb09AM" }
{ "yb": "FDrORkf-Ke65vMt4ggl9tGbnGIrnWA-38DE3yg_oUCo", "ad": "CHN2MSByZXNwAWMd5D9Gi_akdrE-blfMGdQ", "tb": "fd7bL7dlLtJnK9h3Uw4I_fAJK9bXKgvphYL5dAaj95Q" }
{ "ta": "JD-Bdfq9dX4ywcLGxxQE62m5qix1WVSN5YXakmUGoDY" }Each session allows exactly one CPace run (04 §11.7). Any failure aborts the session, erases all CPace state and is recorded locally as crypto.pake_failed; trying again needs a new session with a new QR secret and code. A relaying server therefore gets one guess per device, 1 in 10^6 with a code. Never say which device or digit was wrong. SPAKE2 is not a fallback (04 §11.8). Offer QR pairing first, because only its 128-bit secret resists a future quantum attacker who recorded the transcript (04 §17.3).
Argon2id
The KeyBackup key is derived with Argon2id (04 §12.1):
| Parameter | Producers use | Verifiers accept |
|---|---|---|
| Version | 0x13 (19) |
0x13 only |
Memory m |
65,536 KiB (64 MiB) | 65,536 to 262,144 KiB |
Passes t |
3 | 3 to 10 |
Parallelism p |
1 | 1 only |
| Salt | 16 random bytes | Exactly 16 bytes |
| Output | 32 bytes | 32 bytes only |
The recommended password is the raw 10-byte recovery-phrase entropy, so spelling and case can never change the key, and the output is used only as the PRK of sv1 backup. A client refuses to run or create a computation outside the accepted range before running Argon2id, because the upper limits stop a malicious server from exhausting a phone's memory. Use a new random salt whenever the phrase changes; while it stays the same you may reuse the salt and cache the derived key, so rewriting the KeyBackup doesn't run Argon2id again.
The parameters are stored as an Argon2idParams object, the KeyBackup's kdf member (04 §12.2):
{ "alg": "argon2id", "v": 19, "m": 65536, "t": 3, "p": 1, "salt": "EBESExQVFhcYGRobHB0eHw" }A home server receiving it (for example on PUT /v1/me/backup) refuses out-of-range parameters with 400 crypto.kdf_params_rejected, or 400 crypto.unsupported_algorithm for an unknown alg or v.
Note
§12.1 item 1 records a client's local refusal of any parameter outside the accepted column, version included, as crypto.kdf_params_rejected; §12.2 and §15.1 call an unknown v crypto.unsupported_algorithm. For a server checking an upload, §12.2 item 3 is the specific rule.
Expect 1 to 3 s on a phone and up to about 5 s in WebAssembly on a low-end device (04 §12.3). Run it off the UI thread (a Worker on the web), never in a notification extension. If memory can't be allocated, offer approval from another device; never retry with lower parameters. Vector V-10 gives the output 44f27806a25cb5c97718d68b8654453dd843ee130bd4ab22d327ec16ca8dd504 for password 00010203040506070809 and salt 101112131415161718191a1b1c1d1e1f.
Randomness and key handling
- Every key, nonce, salt,
jti,did,joinNonceand pairing code comes from the operating system's CSPRNG (getrandom(2),SecRandomCopyBytes,crypto.getRandomValuesand so on), neverMath.randomor a timestamp. If the CSPRNG fails, abort; there is no fallback (crypto.rng_failure, 04 §13). - Draw a uniform integer below
N(for exampleN = 1,000,000for a pairing code) by drawingr = u32, redrawing whiler ≥ floor(2^32 / N) · N, and then takingr mod N;r mod Nwithout the rejection step is biased. - Deterministic randomness for reproducing test vectors exists only in test builds and must not be reachable in production builds.
- Each key has only the uses 04 §14.1 lists: the identity key signs only
sv-idcert+jwt,sv-devcert+jwtandsv-devrevoke+jwt; the DSK signs MLS,sv-devproof+jwtand labelled signatures; the box key only opens HPKE. - Keep secret keys non-extractable, or wrapped under a non-extractable platform key, with AAD binding purpose, address and
did; on the web, a non-extractable WebCrypto key in IndexedDB (04 §14.2). Without a platform key store, keep keys in a file readable only by the running user (mode0600) and record that protection is software-only. A DSK or box key never leaves its device. The identity key is extractable by design, because pairing and the KeyBackup move it, so keep it wrapped and unwrap it only for the operations that need it, then erase it. - Erase secrets as soon as they are no longer needed, holding them in mutable byte arrays, never strings (04 §14.3).
- Compare tags and commitments in constant time, and keep keys, plaintext, phrases, pairing values and bearer tokens out of logs (04 §14.4, §14.5).
Use a reviewed library rather than implementing primitives yourself, and pass the vectors either way (04 §14.6). Platform details are on Client requirements and server key storage on Running a server.
Errors
Document 04 owns the crypto area. Every code is HTTP 400, or 401 when the JWS is the request's credential (04 §15.1):
| Code | retryable |
userAction |
|---|---|---|
crypto.malformed (reason: encoding, length, json, structure, size, depth) |
false | none |
| crypto.header_rejected | false | none |
| crypto.unsupported_algorithm | false | update_app |
| crypto.wrong_type | false | none |
| crypto.unknown_key | Server class: true, retryAfterMs 60,000; otherwise false |
Server class: retry; otherwise none |
| crypto.invalid_key | false | none |
| crypto.bad_signature | false | none |
crypto.invalid_claims (reason: missing, type, forbidden, order, lifetime, array) |
false | none |
| crypto.expired | true | retry |
| crypto.not_yet_valid | true | retry |
| crypto.kdf_params_rejected | false | update_app |
{
"type": "urn:sloppyv:error:crypto.malformed",
"code": "crypto.malformed",
"title": "Malformed cryptographic object",
"status": 400,
"detail": "The blob length isn't a length SVF1 can produce.",
"retryable": false,
"retryAfterMs": null,
"userAction": "none",
"data": { "field": "blob", "reason": "length" }
}Never show crypto.* text to the user; retry a retryable code once, then show the generic copy for the failed action. A server never reveals anything about secret values in detail or data, such as which bytes of a tag differed. A server that fails to verify an object it fetched from a third party answers with the owner's peer error, such as 503 federation.issuer_unreachable, not a crypto.* code, and records the crypto.* code as a diagnostic, so a misbehaving peer can't make an honest client look at fault (04 §15.1 item 4, §18 item 16).
Three codes are local diagnostics only, never sent over HTTP or WebSocket; they appear in local logs, SDK error values and uploaded diagnostics with a reason (04 §15.2):
crypto.decrypt_failed:tag,commitment,format,padding,content_hash;crypto.pake_failed:malformed,version,peer_mismatch,identity_element,confirmation,timeout;crypto.rng_failure:unavailable,error. The error object itself is on HTTP API.
Test vectors
The vectors printed in 04 §16.3 are normative; an implementation that disagrees with any of them isn't conforming. Most use K1, RFC 8032 §7.1 test 1 (public key d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a).
| Vector | Covers |
|---|---|
| V-1, V-2 | Strict base64url; JWK thumbprint |
| V-3 (3a–3o) | The JWS profile, time boundaries and every rejection case |
| V-4 (4a–4k) | Strict Ed25519: small-order, mixed-order and non-canonical keys and R, S ≥ L, the cofactor split |
| V-5, V-6 | Labelled signature; ekid, K_msg, kc and the DM context ID |
| V-7, V-8, V-9 | AES-256-GCM; padding buckets; SVF1 and its failure cases |
| V-10 | Argon2id, chained into sv1 backup |
| V-11 (11a–11d) | CPace confirmation, full runs with code and QR secret, a wrong code |
| V-12 | HPKE VaultKeyGrant |
Machine-readable files are meant to live in spec/vectors/<NN>-<topic>.json (for example spec/vectors/04-crypto.json). That directory is still pending, so for now you transcribe the printed vectors (04 §16.1). A file (TestVectorFile) has format "sv1-test-vectors", formatVersion 1, suite "sv1-c1", document and vectors. In each TestVector, a member-name suffix sets the encoding: Hex, B64 or Utf8 (04 §16.2).
{
"id": "04-thumbprint-1",
"section": "§5.2",
"operation": "jwk-thumbprint",
"description": "RFC 8032 test 1 public key",
"inputs": { "publicKeyHex": "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a" },
"expect": "value",
"outputs": { "thumbprintB64": "kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k" },
"status": "final"
}The post-quantum path
Algorithms change only by a new suite, chosen per object or context at creation and never downgraded (04 §17). Recorded X25519 traffic (MLS epoch secrets and everything under them, HPKE grants, code-based pairing transcripts) is at risk from a future quantum computer; AES-256-GCM, SHA-256, HKDF, HMAC and Argon2id are not. The planned sv1-c2 adds a hybrid X25519 and ML-KEM-768 MLS ciphersuite, a 256-bit SFrame suite and a hybrid PAKE, keeping Ed25519 so identities don't change. Until then a v1 implementation rejects every unknown suite, algorithm, format version and parameter set, keeps its primitive choices isolated in code so a new suite doesn't touch protocol logic, and never accepts, produces or tries an sv1-c2 object (04 §17.4). The wider threat model is on Security model.