Lesson 02 · Developers

How device encryption protects your secrets

about 11 minutes

This lesson covers client-side encryption as an engineer has to build or evaluate it: authenticated encryption, key hierarchies, password-based key derivation, platform key stores, and the decryption boundary where cryptographic protection ends. The emphasis is on the last part, because agents and browser automation sit exactly on that boundary. By the end you should be able to write a threat model for an encrypted vault and say precisely which threats move from “solved by cryptography” to “solved by something else” once a secret is in use.

Terms and states

Encryption transforms plaintext into ciphertext under a key. Authenticated encryption with associated data (AEAD) also detects tampering, and lets you bind ciphertext to context (the associated data) that is authenticated but not encrypted. OWASP’s guidance is to use authenticated modes, with GCM and CCM as first preference, and to fall back to CTR or CBC only with separate authentication such as Encrypt-then-MAC [3].

Data is at rest, in transit or in use. Storage encryption handles the first, TLS the second. Nothing in conventional cryptography handles the third: the program that uses a secret must hold the plaintext or a usable key handle.

Client-side encryption (also “on-device” or “end-to-end” in vault products) means the client encrypts before upload and the server never holds keys capable of decrypting user data. The security claim is about who can decrypt, not about whether the data is encrypted somewhere.

Platform storage encryption

NIST SP 800-111 classifies storage encryption into full disk, volume or virtual disk, and file or folder encryption, and frames the choice by storage type, data volume, environment and threats [1]. On Android, file-based encryption splits storage into Credential Encrypted (CE) storage, the default location, “only available after the user has unlocked the device”, and Device Encrypted (DE) storage, available during Direct Boot as well [6]. CE keys are managed by the platform per user and tied to the lock-screen credential.

Two consequences for application developers. First, platform encryption protects a powered-off or locked device; it does nothing once the user is signed in and your process is running. Second, data you put in DE storage for convenience is available before first unlock, so secrets do not belong there.

Key hierarchy

A practical client-side design has at least three layers:

master password ──KDF──▶ key-encryption key (KEK)       never stored
                                │ wraps
                                ▼
                       data-encryption keys (DEKs)      stored wrapped, per record or per vault
                                │ encrypt (AEAD)
                                ▼
                           ciphertext records           synced to server

Envelope encryption (DEKs wrapped by a KEK) lets you rotate the KEK, for instance after a master-password change, by re-wrapping DEKs instead of re-encrypting every record. OWASP recommends storing keys separately from the data they protect, keeping KEKs separate from DEKs, and keeping multiple keys “fully independent from each other” [3]. NIST SP 800-57 Part 1 is the reference for the full key lifecycle, including cryptoperiods, the period a key is authorised for use, and what each key type needs in protection [2].

Deriving the KEK

The KEK is derived from the master password with a memory-hard key derivation function (KDF). RFC 9106 specifies Argon2 and gives two recommended Argon2id settings: the first recommended option is t=1 iteration, p=4 lanes, 2 GiB of memory; the second, for memory-constrained environments, is t=3, p=4, 64 MiB [4]. OWASP’s password storage guidance gives a lower floor for server-side password hashing (Argon2id with 19 MiB, t=2, p=1, or PBKDF2-HMAC-SHA256 at 600,000 iterations where FIPS compliance is required) [11]. For a client-side vault KDF, where the only thing standing between a stolen ciphertext blob and an offline guessing attack is this function, err toward the RFC 9106 settings and tune to the slowest device you support.

Illustrative implementation

# Illustrative envelope encryption. Requires: cryptography, argon2-cffi.
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from argon2.low_level import hash_secret_raw, Type

def derive_kek(master_password: bytes, salt: bytes) -> bytes:
    # RFC 9106 second recommended option: t=3, p=4, m=64 MiB (memory_cost is in KiB)
    return hash_secret_raw(master_password, salt, time_cost=3, memory_cost=64 * 1024,
                           parallelism=4, hash_len=32, type=Type.ID)

def seal(record: bytes, kek: bytes, record_id: bytes) -> dict:
    dek = AESGCM.generate_key(bit_length=256)
    n1, n2 = os.urandom(12), os.urandom(12)              # 96-bit random nonces, never reused per key
    ct = AESGCM(dek).encrypt(n1, record, record_id)      # AAD binds ciphertext to its record id
    wrapped = AESGCM(kek).encrypt(n2, dek, b"dek:" + record_id)
    return {"ct": ct, "n1": n1, "wrapped_dek": wrapped, "n2": n2}

def open_record(box: dict, kek: bytes, record_id: bytes) -> bytes:
    dek = AESGCM(kek).decrypt(box["n2"], box["wrapped_dek"], b"dek:" + record_id)
    return AESGCM(dek).decrypt(box["n1"], box["ct"], record_id)  # raises InvalidTag if swapped or altered

Two details carry real weight. Using the record identifier as associated data means a malicious server cannot swap ciphertext between records without detection. And a fresh DEK per record keeps each key’s message count trivially low, which sidesteps GCM’s limits on invocations and nonce uniqueness that OWASP flags with reference to NIST SP 800-38D [3].

Non-extractable keys in the browser

The W3C Web Cryptography API lets a page generate a CryptoKey with extractable: false, meaning the raw key bytes cannot be exported by script [9]:

// The key can be used by script on this origin, but its bytes cannot be exported.
const key = await crypto.subtle.generateKey(
  { name: "AES-GCM", length: 256 }, /* extractable */ false, ["encrypt", "decrypt"]);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ct = await crypto.subtle.encrypt({ name: "AES-GCM", iv }, key, plaintextBytes);

This is a genuine improvement: an XSS payload cannot copy the key off the machine. It is also a precise illustration of the decryption boundary. Non-extractable restricts export, not use. Any script running in the origin can still call decrypt. The specification’s own security considerations warn that once a key is shared to another origin it cannot be revoked, and that under script injection an attacker can direct cryptographic operations using the key [9]. “Can use but cannot reveal” is a meaningful property, and it does not survive a compromised execution environment.

The decryption boundary

Everything above protects ciphertext. The threat model changes the instant you decrypt.

Memory. Halderman et al. showed that DRAM retains contents for seconds after power loss, longer when cooled, and recovered disk-encryption keys from memory images using cold reboots [5]. Their result “limits the ability of an operating system to protect cryptographic key material from an attacker with physical access”. Vault vendors document the same constraint from the other side. Bitwarden’s white paper states that its User Symmetric Key “is kept in memory while the app is unlocked in order to decrypt vault data”, that keys are purged “as aggressively as possible” on lock, and that some memory cleanup is left to underlying systems “when it is outside our control” [7]. In garbage-collected runtimes and browsers you generally cannot guarantee zeroisation; design so that plaintext lifetime is short and scoped, not so that it is zero.

Autofill. Filling a credential into a page moves plaintext into the DOM, where page script, extensions with host permissions and automation frameworks can read it. Silver et al. showed in 2014 that some autofill policies let a network attacker extract multiple passwords without user interaction [10]; Oesch and Ruoti’s 2020 re-evaluation of thirteen browser-based managers found improvement but persistent issues including unencrypted metadata, insecure defaults and clickjacking exposure [8].

Agents. For an AI agent, there are two very different ways to “use” a secret:

Pattern Where plaintext ends up Main residual risk
Secret returned to the agent as a tool result The model’s context window, provider logs, any transcript Prompt injection can route it to any egress tool; it may persist in logs
Secret filled into the target page by a separate component The page DOM and browser memory Anything with page-read or browser-control access, including the agent if it has a browser tool
Secret used server-side to mint a scoped, short-lived token for the agent Only the token reaches the agent Token misuse within its scope and lifetime

The first pattern defeats the purpose of encrypting the secret at all. The second keeps the stored secret out of the model but not out of the page. The pass privacy policy describes its own design in these terms: approved logins are filled in the browser without the agent receiving stored passwords, and software that can read or control the page may still read a filled login [12]. The third pattern, covered in the API keys lesson, is the strongest where the target service supports it.

Threat model summary

Threat Mitigated by client-side encryption? What actually mitigates it
Server database exfiltration Yes Ciphertext only; strong KDF limits offline guessing
Malicious or compelled provider Mostly, for content Client-side keys; but the provider ships the client code, so code integrity and update channels matter
Lost or stolen powered-off device Yes Platform encryption plus app-level lock
Weak or reused master password No KDF cost buys time; password strength and MFA on the account
Malware or hostile extension on an unlocked device No Endpoint hygiene, extension policy, short unlock windows
Agent with browser control after fill No Don’t combine credential fill with page-reading tools in one agent; separate browser profiles
Metadata (site lists, timestamps, sizes) Product-dependent Encrypt metadata too; minimise what the server must see
Key loss Works against the user Recovery design: recovery keys, emergency access, export

Note the second row. Client-side encryption moves trust from the provider’s servers to the provider’s client code. A provider that can push an update can, in principle, push one that exfiltrates keys. Reproducible builds, signed releases and a small, reviewable client reduce that risk; nothing removes it entirely.

Worked example: auditing a vault design

A small agency is evaluating a vault for shared client logins and wants to let an internal agent run monthly report downloads. Questions, in order:

  1. KDF and parameters. Argon2id at RFC 9106 settings, or PBKDF2 at a documented iteration count? Can the iteration count be raised later?
  2. Key separation. Are DEKs per item or per vault, and wrapped by a KEK that never leaves the device?
  3. AEAD with binding. Is ciphertext bound to item identifiers, so a malicious server can’t swap entries?
  4. Metadata. Are URLs and item names encrypted?
  5. Unlock lifetime. What is the idle lock default, and is the key purged on lock?
  6. Agent path. Does the agent ever receive the plaintext password as a tool result? If the vault fills it into a page, does the agent also have browser read or control tools on that page?
  7. Recovery. What happens if the master password is lost?

For the report agent, the agency picks a design where the agent never holds a stored password and never shares a browser profile with credential fill; where the reporting service offers an API token with read-only scope, it uses that instead.

Key takeaways

Client-side encryption, done properly with AEAD, a memory-hard KDF and an envelope key hierarchy, makes a server breach yield ciphertext and moves the critical secret to the user’s master password and device. Every protection it offers ends at the decryption boundary: once a key is in memory or a secret is in a form field, only process isolation, endpoint security and access policy stand between it and other code. Non-extractable keys and fill-without-reveal designs are real improvements because they separate using a secret from disclosing it, but both fail open if the surrounding execution environment, such as a page an agent can read, is compromised. When agents are involved, the design question is which component ever holds plaintext, and the strongest answer is that no agent-facing component does.

How primitive approaches this. The pass privacy policy describes its vault in the terms used in this lesson: “Primitive Pass encrypts your vault on your device before it is uploaded”, the server “does not have the vault keys needed to read a locked vault”, and where recovery is available “it relies on the user’s Recovery Key and re-wrapping of the user’s key material” [12]. It also states that “Sign-in uses OPAQUE, so your master password is not sent to or learned by the server” [12]; OPAQUE is an augmented password-authenticated key exchange, published by the IRTF as RFC 9807, designed to hide “the password from the server, even during password registration” [13]. These are primitive’s own statements.

Sources and further reading

  1. Scarfone, K., Souppaya, M., & Sexton, M. (2007). Guide to Storage Encryption Technologies for End User Devices (NIST SP 800-111). NIST. https://csrc.nist.gov/pubs/sp/800/111/final
  2. Barker, E. (2020). Recommendation for Key Management: Part 1 – General (NIST SP 800-57 Part 1 Rev. 5). NIST. https://csrc.nist.gov/pubs/sp/800/57/pt1/r5/final
  3. OWASP Cheat Sheet Series. (n.d.). Cryptographic Storage Cheat Sheet. https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html
  4. Biryukov, A., Dinu, D., Khovratovich, D., & Josefsson, S. (2021). Argon2 Memory-Hard Function for Password Hashing and Proof-of-Work Applications (RFC 9106). IRTF. https://www.rfc-editor.org/rfc/rfc9106
  5. Halderman, J. A., Schoen, S. D., Heninger, N., Clarkson, W., Paul, W., Calandrino, J. A., Feldman, A. J., Appelbaum, J., & Felten, E. W. (2008). Lest We Remember: Cold Boot Attacks on Encryption Keys. 17th USENIX Security Symposium. https://www.usenix.org/legacy/event/sec08/tech/full_papers/halderman/halderman.pdf
  6. Android Open Source Project. (n.d.). File-based encryption. https://source.android.com/docs/security/features/encryption/file-based
  7. Bitwarden. (n.d.). Bitwarden Security Whitepaper. https://bitwarden.com/help/bitwarden-security-white-paper/
  8. Oesch, S., & Ruoti, S. (2020). That Was Then, This Is Now: A Security Evaluation of Password Generation, Storage, and Autofill in Browser-Based Password Managers. 29th USENIX Security Symposium. https://www.usenix.org/conference/usenixsecurity20/presentation/oesch
  9. W3C. (n.d.). Web Cryptography API (Level 2), CryptoKey extractable and Security Considerations. https://www.w3.org/TR/WebCryptoAPI/
  10. Silver, D., Jana, S., Boneh, D., Chen, E., & Jackson, C. (2014). Password Managers: Attacks and Defenses. 23rd USENIX Security Symposium. https://www.usenix.org/conference/usenixsecurity14/technical-sessions/presentation/silver
  11. OWASP Cheat Sheet Series. (n.d.). Password Storage Cheat Sheet. https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
  12. Primitive AI (PRIMITIVE AI LABS PTY LIMITED). (2026, 25 October). pass privacy policy, sections 03 (“AI agent access”) and 05. https://pass.primitiveai.com.au/privacy.html (primitive’s own statements; effective 25 October 2026)
  13. Bourdrez, D., Krawczyk, H., Lewi, K., & Wood, C. A. (2025). The OPAQUE Augmented Password-Authenticated Key Exchange (aPAKE) Protocol (RFC 9807). IRTF. https://www.rfc-editor.org/rfc/rfc9807