Skip to content

[Feature] iOS Encrypted Vaults 1/6: crypto / key-wrap core #200

Closed

Description

@libravault-xyz

What problem does this solve?

Sub-issue 1 of 6 from #190's dev-agent triage breakdown — the foundational crypto layer every other iOS Encrypted Vaults sub-issue depends on. Nothing downstream (#2-#6) can start meaningfully until this exists.

Proposed behaviour

Swift equivalent of Android's core:vaultcrypto:

  • Chunked AES-256-GCM encrypt/decrypt via CryptoKit, matching Android's chunk format (see core/vaultcrypto for the reference format — header fields bound into AAD, per-chunk auth)
  • PIN → Argon2id-derived key → wrapped by a Secure Enclave-backed key (iOS's equivalent of Android's StrongBox/TEE Keystore wrap)
  • Independent 256-bit recovery-key wrap path, shown once at creation, never persisted
  • Deterministic per-chunk nonce derivation (HMAC-SHA256 from file id + chunk index), not random — matches Android's structural nonce-reuse-is-impossible guarantee (see NonceUniquenessTest on Android)

Acceptance criteria

  • Round-trip test: encrypt then decrypt recovers original bytes exactly, for files spanning multiple chunks
  • Tamper-detection test: flipping any ciphertext or header byte fails authentication
  • PIN path: Vault Master Key is unwrappable only with the correct PIN + the Secure Enclave key present; never derivable from disk alone
  • Recovery-key path: works fully independently of the PIN/Secure-Enclave path
  • Nonce derivation is deterministic and verified unique across chunks/files in a test

Module / component

iOS app

Does this touch a sensitive area?

Yes — this is the encryption core. Security-labeled on purpose per docs/agent-team-pipeline.md — human scoping required before any implementation.

Activity

  1. added
    enhancement
    status:triage
    security
    on Aug 16, 2026
  2. github-actions commented on Aug 16, 2026

    @github-actions
    Contributor

    Triaged by dev-agent — stopping here, not proceeding to implementation.

    This issue is labeled security (already applied, and the issue body itself calls out "human scoping required before any implementation" for the crypto core). Per .github/agent-policy.yml's sensitive_issue_labels and the dev-agent persona's triage rules, security-labeled issues are never implemented autonomously — they route to status:needs-info for a human to scope and approve the approach first.

    Beyond the policy gate, a few things a human should weigh in on before this gets implemented, since they materially affect the design:

    • Argon2id availability on iOS: CryptoKit does not ship Argon2id. This needs either a vetted third-party implementation (e.g. swift-argon2, or CryptoSwift-style) or a CommonCrypto/libsodium binding — worth deciding which dependency to trust for a KDF this security-critical before code is written.
    • Chunk format parity with core/vaultcrypto: matching Android's chunk format (header fields bound into AAD, per-chunk auth, deterministic HMAC-SHA256 nonce derivation) needs a human or the Android module's author to confirm the exact byte layout so the two platforms stay interoperable — getting this wrong silently breaks cross-platform vault compatibility.
    • Secure Enclave key wrap semantics: iOS's Secure Enclave has different constraints than Android's StrongBox/TEE (e.g. it can't directly wrap arbitrary key material — usually P-256 keys only, requiring an additional key-wrapping scheme layered on top). Worth confirming the intended design matches what Secure Enclave actually supports.

    Applying status:needs-info and leaving security in place. No branch or PR opened.

  3. added
    status:needs-info
    and removed
    status:triage
    on Aug 16, 2026
  4. libravault-xyz commented on Aug 16, 2026

    @libravault-xyz
    CollaboratorAuthor

    Handoff note. Sub-issue 1/6 of #190's iOS Encrypted Vaults breakdown, filed by a human (via Claude Code) following the dev agent's own recommended split — this issue is the dev agent's suggestion, not something it's already scoped further. status:triage + security are both set deliberately: expect the same 'stop and ask a human' outcome #190 got, since implementing this is exactly the kind of encryption/key-management work agent-policy.yml gates. If triage instead proposes a scoping path forward, that'd be a genuine signal this is ready for a human (not the agent) to pick up next — this issue has no code dependencies (it's the foundation), so it's the one sub-issue that could realistically start first.

  5. libravault-xyz commented on Aug 16, 2026

    @libravault-xyz
    CollaboratorAuthor

    Scoping note (human, via Claude Code). Resolving the three open questions from the triage comment above, by reading the actual Android core:vaultcrypto/core:vaultstore source rather than guessing — this is a spec handoff, not an implementation attempt.

    1. Argon2id library

    Decision: vendor the P-H-C reference C implementation directly, at a pinned tagged commit, wrapped in a small SPM C target with a bridging header/module map — not a third-party Swift package. Rationale: wrappers like swift-argon2 are themselves usually just this same C source repackaged into an SPM target, so the trust surface is nearly identical either way; vendoring directly cuts out an extra third-party maintainer/update-cadence dependency to track, and matches Android's own precedent here (core/vaultcrypto's Argon2idKdf.kt uses BouncyCastle — a portable, correctness-first choice over a native lib — with an explicit TODO noting a native swap is a future perf consideration, not a security requirement). Carry the reference impl's license file (dual CC0/Apache-2.0 — compatible with our GPL-3.0).

    2. Chunk format parity — exact byte layout from core/vaultcrypto (Android)

    Read directly from VaultFormat.kt, AesGcmCipher.kt, FileContentKey.kt, VaultKeyMaterial.kt, KeyWrap.kt:

    Per-file header (30 bytes, unencrypted, every field bound into AAD):
    formatVersion:1 | cipherId:1 | fileId:16 | chunkSize:4 (big-endian) | totalPlaintextLength:8 (big-endian)

    • FORMAT_VERSION = 1, CIPHER_AES_256_GCM = 1, KDF_ARGON2ID = 1
    • DEFAULT_CHUNK_SIZE = 32 KiB (validated on-device: lets a PDF proxy-fd open in ~100ms decrypting only the needed chunks of a large file)
    • TAG_SIZE_BYTES = 16, NONCE_SIZE_BYTES = 12, VMK_SIZE_BYTES = 32, RECOVERY_KEY_SIZE_BYTES = 32, ARGON2_SALT_SIZE_BYTES = 16, FILE_ID_SIZE_BYTES = 16 (random, collision-free)

    Per-chunk AAD (binds header fields into every chunk, not just once — a truncated/spliced/reordered file fails AEAD on the first chunk, not just at the end):
    formatVersion:1 | cipherId:1 | chunkSize:4 | fileId:16 | totalPlaintextLength:8 | chunkIndex:8 | isFinalChunk:1 = 39 bytes total, built from what the file's own header says, not the build's current constants (so future format versions can still be read).

    Per-chunk nonce — deterministic, never random:
    nonce = HMAC-SHA256(key = fileContentKey, "vaultcrypto-nonce-v1" || chunkIndex:8)[0..12]
    Deterministic-by-design: a different chunk index within a file always gives a different nonce; a different file has an entirely different key, so nonce spaces never overlap. (Swift: CryptoKit.HMAC<SHA256>.)

    Per-file content key (never the VMK directly):
    fileContentKey = HKDF(salt = FILE_CONTENT_HKDF_SALT, ikm = VMK, info = "vaultcrypto:file-content:v1" || fileId, len = 32) — CryptoKit.HKDF covers this directly.

    Key wrap (VMK wrapping, both the KEK path and the recovery path) — AES-256-GCM with a fresh random nonce per wrap (not deterministic — wraps happen once at creation/PIN-change, not per-chunk, so there's no reuse-risk to design around):

    • wrappedVmkByKek = AES-GCM-wrap(key = Argon2id(pin, salt, params), plaintext = VMK, aad = "vaultcrypto:vmk-wrap:kek:v1")
    • wrappedVmkByRecovery = AES-GCM-wrap(key = recoveryKey, plaintext = VMK, aad = "vaultcrypto:vmk-wrap:recovery:v1")
    • Distinct AAD per path so one wrapping can never be substituted for the other.

    Argon2id default params (Argon2Params.DEFAULT on Android — provisional, tuned to ~750-850ms on budget hardware): memory = 19 MiB, iterations = 2, parallelism = 1. Carry the same defaults on iOS for now (params are stored per-vault in the header, so this can change later without breaking existing vaults) — but this needs its own on-device benchmark pass on real iPhone hardware before shipping, same as Android's own outstanding TODO here; don't assume the numbers transfer.

    Error semantics worth mirroring: a failed AEAD tag (wrong PIN/tamper) and a wrong-length truncation are surfaced as distinct exception types but with a deliberately identical, non-specific message for the AEAD case — Android's comment calls out that "wrong PIN" vs "tampered file" is itself a side channel worth not exposing. An unrecognized formatVersion must fail closed, not attempt to interpret the bytes.

    3. Secure Enclave wrap semantics

    Android's HardwareKeyWrap (core/vaultstore) is an interface — wrap(plaintext) -> WrappedBlob, unwrap(wrapped) -> ByteArray, plus an isHardwareBacked: Boolean reported at wrap time, with an explicit fail-closed-not-silently-downgrade policy: if hardware backing isn't available, the caller must require a stronger passphrase rather than proceed as if a 4-digit PIN were still safe. This wraps wrappedVmkByKek a second time (Argon2id KEK wrap, then Keystore wrap on top) — the recovery-key wrap deliberately bypasses this layer entirely so it survives Keystore key loss.

    iOS's Secure Enclave can't directly wrap arbitrary symmetric key material the way Android Keystore can (it's constrained to P-256 key operations). The equivalent construction:

    1. Generate a non-exportable P-256 key pair in the Secure Enclave (SecKeyCreateRandomKey with kSecAttrTokenIDSecureEnclave), gated by an access control flag (.privateKeyUsage, biometry-or-passcode).
    2. ECDH between the SE private key and a device-local ephemeral/static public key to derive a shared secret (SecKeyCopyKeyExchangeResult).
    3. HKDF the shared secret into a symmetric AES-256 key.
    4. Use that key to AES-GCM wrap the KEK-wrapped VMK blob, mirroring Android's "wrap the wrap" shape and the same isHardwareBacked fail-closed contract.

    Recommend implementing this behind the same interface shape as Android's HardwareKeyWrap (real SE-backed impl + a fake/in-memory impl for host-side unit tests, mirroring FakeHardwareKeyWrap) so VaultStore's orchestration logic (#201) stays testable off-device the same way Android's is.


    No branch/PR opened — this is a spec handoff for whoever picks up #200 next (human or a dev-agent run explicitly un-gated by a human choosing to remove the security label for this issue specifically). Round-trip + tamper-detection tests should mirror Android's ChunkedVaultRoundTripTest/TamperDetectionTest/Argon2idKdfTest/NonceUniquenessTest in shape.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementiossecuritystatus:needs-info

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions