E2E key management that never loses a key (keyring, backup, re-wrap)
e2ekey-backupkeyringpbkdf2logoutshared-preferencesmulti-device
In an end-to-end encrypted app the hard part is not the cipher, it is key custody: every device, every logout, every password change, and every reinstall is a chance to lose the only key that decrypts a conversation. TLDR lost keys several times before converging on the design below. The governing rule became: never discard a key pair, ever.
How keys got lost (the failure catalog)
- Each device generated its own identity (web storage and Android storage never shared it), so messages encrypted for the web key were garbage on the phone and vice versa.
- The backup was wiped on every launch. The app upserted its public key at startup with a
public-only payload, and the server's public-only branch set
encrypted_private_key = NULL. A later "fix" removed a client flag but not the server null, so cross-device restore never had anything to restore. - A stale "already uploaded" flag in local prefs predated the backup feature and short-circuited the upload forever. Errors in the upload were also swallowed.
- Logout destroyed unbacked keys: keys were "preserved" and then
reset()wiped them because the restore ran before the reset. - A singleton's
_initializedguard survived logout, so the next login skipped the backup-migration path entirely. - A debug reinstall wiped app data on a real phone. See Debug installs wipe app data, and recovering it with Android Auto Backup.
The design that holds
- Password-wrapped backup on the server. Each private key is encrypted with a key derived from the user's password (PBKDF2 with a random salt, then AES-GCM) and stored server-side. The server cannot read it. Login returns the wrapped blob and salt so a new device can restore.
- Keyring, not a key. The client holds every key the user has ever had. One is canonical (used to encrypt and published); decryption tries every key in the ring until one works.
- Append-only archive table (
dm_key_archive: username, public key, wrapped private key, salt). Rows are never UPDATEd or DELETEd. One row per (public key, password wrap). Insert is idempotent; a check-then-insert race can at worst duplicate a row, never lose one. - Upserts preserve backups. A public-only upsert keeps the existing wrapped key unless the
public key actually changed:
encrypted_private_key = IF(public_key = VALUES(public_key), encrypted_private_key, NULL)(MySQL/MariaDB evaluate SET clauses left to right, so this reads the pre-update value as long as it is assigned beforepublic_key). - Login self-heal (
_syncKeyRingWithServer): restore every archived key that decrypts under the current password, back up this device's local key, keep the published key if its private half is in the ring (so a password change does not rotate identity), and for any ring key with no current-password wrap, re-wrap and append. Every wrap is round-trip verified before upload. - Change password reuses the self-heal with the new password instead of a separate re-encrypt
function (the old
reEncryptPrivateKeywas uncalled and diverged, and was deleted).
Local storage rules
- Namespace key slots by username (
dm_x25519_private_<user>etc.). Un-namespaced slots let user B on a shared device load user A's keys. Migrate legacy slots once, then delete them. - Identity guard:
initialize()short-circuits only for the same user; a different user forcesreset()first. Any 401/expired-session handler must also reset crypto state. - Logout invariant:
exportKeys(user)beforeprefs.clear(), thenreset(), thenimportKeys(user)after. Getting this order wrong is exactly how failure 4 happened. - Never swallow errors in backup/upload paths; a silent failure here is data loss later.
Residual limits (inherent to E2E)
- A fresh device whose first login is after a password change cannot open the archive (wrapped under the old password) and has no raw key, so it rotates identity; history un-strands when any device that holds the raw keys logs in and re-wraps.
- The self-heal needs a successful archive fetch; if the fetch fails, skip healing rather than
acting on an empty list (distinguish
null= failed from[]= empty). - Users who never logged in after the backup feature shipped have nothing on the server to heal.
- Passwordless sign-in (emailed links, Email sign-in links (one-time "magic links")) authenticates without the password, so it can never unwrap a backup. A client that finds no cached key and has no password must not generate a new key pair: ask the server whether a key is already published, and if one is (or the check fails), lock messaging on that device and ask for the password. Otherwise a fresh key gets published over the real one.
Admin password resets
An admin who sets a new password directly in the database leaves every wrap under the old
password, so the user's next fresh device would rotate identity. The server can fix that only if
some password that opens an existing wrap is known (for example the previous password from an
earlier admin reset): export the archive, unwrap with the old password and check the result
matches the published public key, re-wrap under the new password with a fresh salt and nonce,
round-trip it, then append it as a new archive row and update the canonical bundle (public key
unchanged). Back up the key rows first. Without a known old password this is impossible by design;
the fallback is a login on a device that still holds the raw key (self-heal), or rotation. On TLDR
this was done once with a one-off Dart tool using the same cryptography package as the app
(2026-11-07); its copy lives in tldr project memory.
Operating procedures
- Back up the key tables before any crypto change (
mysqldumpof the bundle and archive tables, copied off-box), and verify the dump. - Keep verification tooling: an export script (prod, read-only, to JSON) plus a verifier that uses the real crypto library and reports OK / LOCKED / CORRUPT per row, exiting 0 only if every distinct public key has a current-password-decryptable wrap.
- Ship data-safety fixes to production before device testing, so the safety net exists before anything can go wrong.
See also
- Simple E2E messaging with X25519 + HKDF + AES-GCM (and why not Signal)
- E2E group chat with per-epoch sender keys
- Migrating legacy password hashes to bcrypt on login
Linked from
- Debug installs wipe app data, and recovering it with Android Auto Backup
- E2E group chat with per-epoch sender keys
- Email sign-in links (one-time "magic links")
- Migrating legacy password hashes to bcrypt on login
- Passphrase-encrypted export files for moving app data between phones
- Simple E2E messaging with X25519 + HKDF + AES-GCM (and why not Signal)
- Singleton services, session caches, and cross-user data leaks in Flutter
- Storing saved passwords, cards and tokens in an Android app
- TLDR platform architecture (tldrnerd.com)