# Sealed: encryption and key handling

A specification of how Sealed (the iPhone app, internally "BlackboxVault") encrypts what you put in it and how it handles the key.
It is written so that a reviewer can check what Sealed claims, and so that someone with the key can decrypt a Sealed **file** (a blob or a
share) with their own code. Names, stacks and file types live in sealed values whose JSON field names are in Appendix A. Every format below,
except the Secure Enclave mode (section 5.2), the passcode verifier (section 10) and the JSON of Appendix A, is checked by test vectors
(`vectors.json`, section 13) that were produced by the app's own code and decrypted again by an independent implementation
(`verify_vectors.py`) that was written from this text alone.

- **Applies to:** Sealed 1.0.0.
- **Status:** the formats of 1.0.0 are in the shipped app and will not change incompatibly. Versioned, with a byte a reader must check and
  refuse when it is unknown: the file blob (`BBXV`, section 4) and the encrypted share (`BBVS`, section 9). Not versioned: the sealed
  value (section 0), the passcode verifier (section 10, a JSON object), the key check (its label ends in `v1`), and the recovery phrase
  (section 6).
- **Not covered:** the user interface, billing, and the lock-screen behavior that is not cryptographic.

## 0. Conventions

- Integers are big-endian ("BE"). `a || b` is concatenation. Strings are UTF-8. Hex in this document is lowercase.
- **Sealed value (SV).** `AES-256-GCM` with a 12-byte random nonce and a 16-byte tag, serialized as
  `nonce(12) || ciphertext(n) || tag(16)`, with no associated data unless a section says otherwise. This is the "combined" form of
  CryptoKit's `AES.GCM.SealedBox`. A reader opens it with the 32-byte key and fails the whole value if the tag does not verify.
- **The vault key** is written `K`: 32 bytes.
- A sealed value is at least 28 bytes (nonce and tag). Cryptographic comparisons of secrets are constant-time.

## 1. Primitives

| Use | Primitive |
|---|---|
| Bulk and small-value encryption | AES-256-GCM (Apple CryptoKit) |
| Key check | HMAC-SHA-256 (CryptoKit) |
| Passphrase to key (encrypted shares) | PBKDF2-HMAC-SHA-256 (CommonCrypto) |
| Hardware-bound mode (Maximum Security) | ECIES on a P-256 Secure Enclave key: Apple `SecKeyAlgorithm.eciesEncryptionCofactorX963SHA256AESGCM` |
| Randomness | the system generator, through CryptoKit's `SymmetricKey(size: .bits256)` and `SecRandomCopyBytes` |

Sealed uses no other cryptography. It does not implement any primitive itself except the iterated hash of section 10.

## 2. Keys

- **Vault key `K`.** 32 random bytes made on the device during setup. It is not derived from a passcode, a password or anything else the
  person types. It never leaves the device: it is not sent to Apple, to Sealed, or to anyone, and the iCloud backup (section 8) does not
  contain it. It exists in these forms: the plaintext Keychain item (section 5.1), the copy sealed to the Secure Enclave
  (section 5.2), and the recovery key the person writes down (section 6; it is `K` itself).
- **File key (DEK).** 32 random bytes made for each file and each thumbnail, sealed under `K` inside that file (section 4).
- **Gate key.** 32 random bytes in the Keychain, independent of `K`. It seals the few settings that have to be readable while the
  vault is locked: the trusted places of Location Lock, and the location attached to a break-in event. It never protects vault content.
- **Key check.** `HMAC-SHA-256(key = K, message = "sealed.recovery.keycheck.v1")`, 32 bytes, kept in the Keychain. It lets the app confirm
  that a typed recovery key belongs to this vault when `K` itself is not readable (section 5.2). It is one-way.

## 3. Sealed small values

Names, titles, text and records are stored as `SV(K, plaintext)`. This covers: the name of an item and of a stack; bookmark title and
address; a note's title, its body (UTF-8) and its rich-text data; a record's title and its payload (a JSON object); and the payloads of
the iCloud backup (section 8). Each value has its own random nonce.

## 4. Files: the blob format

Photos, videos, documents, voice memos, thumbnails and break-in photos are stored as blobs. A blob is encrypted in chunks so that large
files stream through fixed memory and so that truncation, reordering and tampering are detected.

```
blob   = header || chunk_0 || chunk_1 || ... || chunk_last
header = "BBXV"                       4 bytes  magic
         0x01                         1 byte   version
         dek_len                      2 bytes  BE, the length of wrapped_dek (60 for AES-256-GCM)
         wrapped_dek                  dek_len  SV(K, DEK)        (nonce 12 || ciphertext 32 || tag 16)
         chunk_size                   4 bytes  BE, plaintext bytes per chunk, 1 .. 4194304 (4 MiB)
chunk  = sealed_len                   4 bytes  BE, = plaintext length + 16
         ciphertext                   sealed_len - 16 bytes
         tag                          16 bytes
```

- Each chunk is `AES-256-GCM(key = DEK, nonce = chunk_nonce, plaintext, no associated data)`.
- `chunk_nonce` (12 bytes) is `counter(8 bytes, BE) || 0x00 0x00 0x00 || last(1 byte)`, where `counter` is the chunk's index starting
  at 0 and `last` is `0x01` for the final chunk and `0x00` for every other chunk. The nonce is not stored; the reader recomputes it.
- A writer fills every chunk except the last with exactly `chunk_size` plaintext bytes. The last chunk holds 1 to `chunk_size` bytes,
  except that an empty file is a single last chunk of zero plaintext bytes (`sealed_len` = 16, the tag only). A reader accepts any chunk
  whose `sealed_len` is between 16 and `chunk_size + 16`.
- **Reading.** Parse the header; open `wrapped_dek` with `K`; the DEK must be 32 bytes. Then read chunks in order. A chunk is the last
  chunk exactly when no byte follows it in the file; its nonce must then carry `last = 1`. A reader **refuses** the file when:
  1. the magic is not `BBXV` or the version is not 1;
  2. the file ends inside the header, or `dek_len` is not 60 (the only length a sealed 32-byte key can have);
  3. `wrapped_dek` does not open with `K` (a key that opens is always 32 bytes, because `dek_len` is 60; a reader checks it anyway);
  4. `chunk_size` is 0 or above 4194304;
  5. a chunk's `sealed_len` is below 16 or above `chunk_size + 16`, or the file ends inside a chunk;
  6. a chunk's tag does not verify under the nonce of its position and its last flag;
  7. there are no chunks at all, or the data ends without a chunk that verified as the last one.

  Because the nonce encodes both the position and the end of the stream, reordering chunks, dropping chunks from the end, and appending
  chunks are all rejected. A reader does **not** require every non-final chunk to be full: only that each chunk verifies in its position.
- A writer generates a fresh random file key for every stream it writes and never writes two different streams under one file key: the
  chunk nonces are deterministic, so reusing a key would reuse nonces. A share's stream gets its own file key, sealed under the share key.
- A reader that streams plaintext out hands over early chunks before the last chunk is verified. It must surface the failure at the end and
  must not treat what it was given as a complete file.
- File names on disk are random (a UUID and the extension `.enc`); they carry no information about the content.

## 5. Where the vault key lives

### 5.1 Baseline

`K` is stored as a 32-byte generic-password item in the iOS Keychain (service `com.loopware.blackboxvault`, account `vault.masterkey`),
accessible only while the device is unlocked (`kSecAttrAccessibleWhenUnlockedThisDeviceOnly`): it is not synchronized and does not move
to another device through a backup or a transfer. The app holds `K` in memory only while the vault is unlocked and drops it when the vault locks.

The passcode is a gate in front of the app. It is not part of the key: a person who can read the Keychain item can read `K` whether or
not they know the passcode. (This is why the hardware-bound mode below exists.) The Keychain item is protected by the operating system,
not by Sealed.

### 5.2 Maximum Security (hardware-bound)

An optional mode seals `K` to a Secure Enclave key whose private half cannot leave the chip and can be used only after a live Face ID
or Touch ID match (`.biometryCurrentSet`). The wrapped key is `ECIES(K → P-256 public key)` using
`eciesEncryptionCofactorX963SHA256AESGCM`, stored in the Keychain as `vault.masterkey.sewrapped`; the exported public key is
`vault.masterkey.sepublic`. The plaintext `K` item is deleted only after the app has unwrapped the wrapped copy once and compared it
with the original. In this mode the key check (section 2) is what confirms a typed recovery key without a biometric.

Things that must be written while the vault is locked (a photo taken after wrong passcode attempts) are **staged**: the file is
`"BBSE" || ECIES(jpeg → public key)` in the vault's `staged` folder, and is re-sealed as an ordinary blob at the next unlock.

## 6. The recovery key

### 6.1 Version 1 (Sealed 1.0.0)

The recovery key is `K` written out: `payload = K(32) || SHA-256(K)[:2]` (34 bytes; the checksum is the **first two bytes** of the
SHA-256 of `K`), encoded as Crockford base32 (alphabet `0123456789ABCDEFGHJKMNPQRSTVWXYZ`, five bits per character, most significant bit
first) and shown in groups of five characters separated by hyphens: 55 characters, eleven groups. The 34 bytes are 272 bits; the 55th
character carries the last 2 bits of the checksum and 3 padding bits, which an encoder writes as zero.

A reader **maps the whole input to upper case with full, locale-independent Unicode case mapping** (so U+0131 becomes `I` and U+00DF becomes `SS`), then **deletes
everything that is not an ASCII letter or digit** (hyphens, dashes, spaces, non-breaking spaces and line breaks are formatting), applies the
Crockford aliases `O → 0`, `I → 1` and `L → 1`, and **refuses any remaining letter that is not in the alphabet** (`U`). It decodes five bits
per character and **ignores the 3 padding bits** (so eight final characters decode to the same key). A version 1 phrase decodes to
**exactly 34 bytes** (a phrase one character too long or too short is refused), and its checksum must match.

Because the recovery key is `K`, anyone who holds it and a copy of the encrypted data can read the vault, and it cannot be replaced
without re-encrypting everything.

## 7. Moving between devices

On a new iPhone the Keychain item does not travel (it is device-only). The person types the recovery key; the app decodes it, checks it
against data that came along (a sealed value from the vault, or an iCloud record), installs `K` in the new device's Keychain, and asks
for a new passcode.

## 8. iCloud backup

Backup is optional and goes to the person's own iCloud account (a private CloudKit database in the container
`iCloud.com.loopware.blackboxvault`). Nothing is sent to a server run by Sealed.

| Record type | Fields |
|---|---|
| `VaultItem` | `payload`: SV(K, JSON); `blob`: asset, the blob of section 4 unchanged; `thumb`: asset, the thumbnail's blob |
| `SecureNote` | `payload`: SV(K, JSON); `rtfd`: asset, SV(K, rich-text data), used only when the rich body is too large for a record |
| `SecureRecord` | `payload`: SV(K, JSON) |
| `Album` (a stack) | `payload`: SV(K, JSON) |

The JSON inside a `payload` carries everything about the item: for a vault item its name, type, dates, size, MIME type, duration, stack
membership, favorite flag and the names of its files; for a note its title, body and dates; for a record its type, title and fields.
Nothing is in a separate, readable field. What Apple can see is the record type, a random record name, the usual CloudKit system
fields (creation and modification times of the record, sizes of the assets) and how many records there are. Dates in the JSON use the
default Swift `JSONEncoder` representation (seconds since 2001-01-01 00:00:00 UTC as a number).

Records are written with a conditional save and merged by the item's own `updatedAt`; a deleted item is removed from the zone.

## 9. Encrypted share files (`.bbvshare`)

A share is one item locked by a passphrase, for sending to another person who has Sealed.

```
share  = "BBVS"                       4 bytes  magic
         0x01                         1 byte   version
         salt                         16 bytes random
         iterations                   4 bytes  BE; 600000 when written; a reader accepts 1 .. 2000000
         meta_len                     2 bytes  BE
         sealed_meta                  meta_len SV(S, JSON meta)
         stream                       a blob (section 4) encrypted with key S
S      = PBKDF2-HMAC-SHA-256(password = passphrase as UTF-8, salt, iterations, 32 bytes)
```

- The stream is everything after `sealed_meta`, up to the end of the file. The blob's `wrapped_dek` is sealed under `S`, exactly as a vault
  blob's is sealed under `K`, and the stream gets its own fresh file key.
- `meta` is a JSON object (key order and escaping are not significant). `name`, `typeRaw` and `mimeType` are required strings;
  any other key is ignored. A reader refuses a share whose metadata is not a JSON object, lacks a required key, or has a key of a known
  name with the wrong type. The sender's `name` is only a suggestion: the app turns it into a safe file name and never uses it as a path.
- A wrong passphrase shows up as a failure to open `sealed_meta`.
- A reader **refuses** a share when: the magic is not `BBVS` or the version is not 1; the file ends inside the 27-byte fixed part or inside
  `sealed_meta`; `iterations` is outside 1 .. 2000000; `sealed_meta` does not open with `S`; the metadata breaks the rules above; or the
  stream breaks a rule of section 4.
- The passphrase is used as typed, as UTF-8, with **no** Unicode normalization. A passphrase typed in decomposed form therefore derives
  a different key than the same words typed in composed form.

## 10. Lock-screen credentials

A passcode, a pattern and the credentials of the decoy vault are each stored as a salted, iterated verifier in the
Keychain; a locked stack's verifier is stored in the stack's row in the local database (not sealed there; sealed inside the iCloud payload). They are
an access gate and are not key material. The verifier is app logic, not an interoperable format, and has no test vector.

```
verifier = JSON {"salt": base64(16 random bytes), "iterations": 100000, "hash": base64(32 bytes)}
h_1      = SHA-256(salt || secret)           secret = the passcode or the pattern's dot sequence, as UTF-8
h_(i+1)  = SHA-256(h_i || salt)              for i = 1 .. iterations - 1
hash     = h_iterations
```

Entry is rate-limited: after a set number of wrong tries (three by default) entry is refused for 30 seconds, and for 1, 5, 15 and then 60
minutes after further wrong tries. The count survives a restart, and the cooldown is timed on the monotonic clock so that moving the
phone's date does not shorten it. A pattern is turned into a string (its dots in the order they were drawn) before it is hashed; the exact
string is the app's own and is not specified here.

## 11. What is and is not encrypted on the device

**Encrypted with `K`:** the content of every file and thumbnail (section 4); names of items and stacks; bookmark titles and addresses;
note titles, bodies and rich text; record titles and all record fields; break-in photos; the iCloud payloads.

**Not encrypted by Sealed** (it sits in the app's local database or in the app's preferences, protected only by iOS data protection):

- for each item: its kind, creation, import and modification dates, the original capture date, size in bytes, MIME type, duration,
  favorite flag, which stacks it is in, its soft-delete date, its backup state and the iCloud record name, and the random file names;
- for each stack: its dates, cover item, order, parent stack, and, if it is locked, the verifier of its PIN (section 10);
- for notes and records: dates, favorite flag, and for a record its type (login, card, ...);
- the break-in log: the kind of event, its time and a short text such as "Failed unlock attempt #3";
- the app's settings (which protections are on, the auto-lock interval, the lock style).

**Briefly in the clear while in use:** a decrypted copy of a file while it is viewed, imported, exported or transferred, in a temporary
folder protected by iOS "complete" file protection and deleted when the vault locks and at launch; the contents of the share-extension
inbox and of the USB drop folder until the app imports them; the wireless transfer page, which receives files over plain HTTP on the
local network protected only by a one-time session code.

**Outside the vault by design:** the original photo in the Photos library until the person deletes it, and anything the person exports.

## 12. Known limits (for reviewers)

- Without Maximum Security, the app can read `K` whenever the phone is unlocked, because it sits
  in the Keychain; the passcode does not protect it. An attacker who can run code inside the unlocked app or read the Keychain gets `K`.
- The recovery key is `K`. It cannot be revoked.
- The local database's metadata (section 11) is not encrypted by Sealed.
- The passcode verifier (section 10) is a custom iterated hash rather than a standard password hash. It is a gate and not key material;
  a person with the Keychain contents already has `K` in the baseline mode.
- Sealed values and wrapped file keys carry no associated data. Whoever can write to the iCloud zone or to the device's database can swap
  or roll back whole values undetected: confidentiality is unaffected, the integrity of which value belongs where is not. A later version
  can bind each value to its purpose, record and version.
- The encrypted share's passphrase is not normalized, and PBKDF2-HMAC-SHA-256 is not memory-hard. The file travels through third parties,
  so the passphrase is the only protection once it leaves.
- The wireless transfer page is plain HTTP on the local network.
- Sealed has not had an independent security audit. This document, the vectors and the verifier that was written from it are the
  material an auditor would start from.

## 13. Test vectors

`vectors.json` contains, for each format above, inputs and outputs produced by the app's code:

| Name | What it checks |
|---|---|
| `sealed_value` | sections 0 and 3: open a sealed value with `K` (`plaintext`) |
| `blob_single_chunk`, `blob_multi_chunk`, `blob_exact_multiple`, `blob_empty` | section 4: header, nonces, last-chunk flag, a full last chunk, an empty file |
| `blob_must_fail` | section 4: a reader must refuse each (a dropped last chunk, swapped chunks, an appended chunk, a damaged wrapped key, a header with no chunk, a zero chunk size, a chunk size above 4 MiB) |
| `recovery_key_v1` | section 6.1: encode, accepted spellings (`accepted_inputs`), refused ones (`rejected_inputs`) |
| `key_check` | section 2 |
| `share` | section 9: PBKDF2 (including a non-default number of rounds and a decomposed passphrase), metadata, the stream |
| `share_must_fail` | section 9: a reader must refuse each; `reason` says why (`wrong passphrase`) |

Every vector carries `since`, the version that introduced the format (always `1.0.0` in this edition, whose file says so in `edition`).
They were made by the app's own code, and `verify_vectors.py` was written from this document and this file alone. Fields: `key` is `K`
in hex; `plaintext`, `blob`, `sealed`, `file` are hex; `phrase` is as typed; in a share, `passphrase` and `iterations` are the inputs of
the key derivation (the rounds are also in the file's header) and `meta` is the metadata as JSON; `reason` says why a refused share is
refused; `label` is for people. `blob_must_fail` has seven entries: a dropped last chunk, swapped chunks, an appended chunk, a changed
byte of the wrapped key, a header and no chunk, a chunk size of zero, and one above 4 MiB.

A conforming reader decrypts every vector to the `plaintext` it carries and refuses every `*_must_fail` vector.

## Appendix A: the JSON inside a sealed payload

These are the keys of the JSON a sealed value of the iCloud backup (section 8) decrypts to. All dates follow section 8. Optional keys are
omitted when empty. A reader ignores keys it does not know.

Types: strings, booleans, numbers (dates and `durationSeconds` are numbers, `fileSize` an integer), arrays, and objects as written; `?` marks a
key that is left out when empty.

- **Vault item** (`VaultItem`): `name`, `typeRaw` (`photo`, `video`, `document`), `encryptedFileName`, `encryptedThumbFileName?`, `createdAt`,
  `importedAt`, `updatedAt`, `originalCreationDate?`, `isFavorite`, `fileSize`, `mimeType`, `durationSeconds?`, `albumIds` (UUID strings).
- **Note** (`SecureNote`): `title`, `body`, `rtfd?` (base64), `isFavorite`, `createdAt`, `updatedAt`, `albumIds` (UUID strings), `rtfdInAsset?`.
- **Record** (`SecureRecord`): `recordTypeRaw` (`login`, `totp`, `card`, `bankAccount`, `idDocument`, `wifi`, `recoveryCode`, `licenseKey`, `contact`, `custom`), `title`, `payload` (an object: `username`, `password`, `website`, `cardNumber`, `expirationDate`,
  `cvv`, `accountNumber`, `notes`, `customFields` (an array of objects: `id` (UUID string), `label`, `value`, `isSensitive`), `tags` (an array of strings), and optional `wifiSecurity`, `phone`, `email`, `address`, `company`), `isFavorite`,
  `createdAt`, `updatedAt`, `albumIds` (UUID strings).
- **Stack** (`Album`): `id`, `name`, `sortOrder`, `coverItemId?`, `createdAt`, `lockData?` (the verifier of section 10, base64), `updatedAt?`,
  `parentID?`.
