# CryptoKit: Hashing, MACs and Symmetric Encryption

This file covers the symmetric half of CryptoKit: digests (SHA-2 and SHA-3), HMAC,
the two AEAD ciphers (AES-GCM and ChaChaPoly), `SymmetricKey`, nonce handling, key
derivation with HKDF and PBKDF2, and moving old CommonCrypto code over. The baseline
is iOS 13; HKDF as a standalone type needs iOS 14; SHA-3 needs iOS 26.

Types you will meet below: `SHA256`, `SHA384`, `SHA512`, `SHA3_256`, `HMAC`,
`AES.GCM.seal` / `AES.GCM.open`, `ChaChaPoly.seal` / `ChaChaPoly.open`,
`SymmetricKey`, `AES.GCM.Nonce`, `HKDF`, and the per-cipher `SealedBox`.

## Contents

- [Digests](#digests)
- [HMAC](#hmac)
- [AES-GCM](#aes-gcm)
- [ChaChaPoly](#chachapoly)
- [SymmetricKey](#symmetrickey)
- [Moving off CommonCrypto](#moving-off-commoncrypto)
- [Frequent mistakes](#frequent-mistakes)
- [Post-quantum outlook](#post-quantum-outlook)
- [OWASP mapping](#owasp-mapping)
- [Tests worth writing](#tests-worth-writing)
- [Sources](#sources)
- [Checklist](#checklist)

## Digests

Every hash type conforms to `HashFunction`.

| Family | Types | Availability |
| --- | --- | --- |
| SHA-2 | `SHA256`, `SHA384`, `SHA512` | iOS 13+, macOS 10.15+ |
| SHA-3 | `SHA3_256`, `SHA3_384`, `SHA3_512` | iOS 26+, macOS 26+ (added alongside the WWDC25 release, mirrored in swift-crypto PR #397) |

The open-source swift-crypto package (`import Crypto`) ships SHA-3 for older
deployment targets, but that does not make it available in Apple's framework:
`import CryptoKit` still requires the iOS 26 SDK and runtime. Check which module
you import before assuming availability.

A digest value is a `Sequence` of `UInt8`, conforms to `ContiguousBytes`,
`Hashable` and `CustomStringConvertible`, and its `==` compares in constant time.

```swift
import CryptoKit
import Foundation

let manifest = Data("release-manifest-v4".utf8)
let fingerprint = SHA256.hash(data: manifest)
let hexFingerprint = fingerprint.map { String(format: "%02x", $0) }.joined()

let expected = SHA256.hash(data: Data("release-manifest-v4".utf8))
let matches = fingerprint == expected
```

Build hex strings yourself as above. Do not rely on `.description`; Apple states
its format is not stable.

Large inputs should be streamed so the whole file never sits in memory. Read in
chunks (1 MB works well) and wrap each read in `autoreleasepool` so the
temporary `Data` buffers are released per iteration:

```swift
func digestOfFile(at url: URL) throws -> SHA256.Digest {
    let handle = try FileHandle(forReadingFrom: url)
    defer { try? handle.close() }
    var hasher = SHA256()
    var reachedEnd = false
    while !reachedEnd {
        try autoreleasepool {
            let block = try handle.read(upToCount: 1_048_576) ?? Data()
            if block.isEmpty {
                reachedEnd = true
            } else {
                hasher.update(data: block)
            }
        }
    }
    return hasher.finalize()
}
```

SHA-3 uses the Keccak sponge construction rather than SHA-2's Merkle-Damgard
chaining, but the Swift API is the same. Reach for it when a compliance profile
names it or you want algorithm diversity. Gate it and fall back:

```swift
func contentTag(for payload: Data) -> Data {
    if #available(iOS 26.0, macOS 26.0, *) {
        return Data(SHA3_256.hash(data: payload))
    }
    return Data(SHA256.hash(data: payload))
}
```

Broken hashes live under `Insecure` on purpose. `Insecure.MD5` collisions take on
the order of 2^18 operations (seconds on a laptop), and `Insecure.SHA1` fell to a
practical chosen-prefix collision in 2020 costing roughly $45,000 of GPU time.
Neither belongs anywhere security matters; SHA-256 is the floor.

| Algorithm | Pick it for |
| --- | --- |
| SHA-256 | Default: integrity checks, signatures, HMAC |
| SHA-384 | Certificate chains, extra margin |
| SHA-512 | Large data, faster on 64-bit cores |
| SHA3-256 | Compliance requirements naming SHA-3 |
| SHA3-384 | Longer-term margin |
| SHA3-512 | Highest-assurance profiles |
| MD5, SHA-1 | Broken. Only for legacy, non-security checksums |

## HMAC

`HMAC<H>` is generic over any `HashFunction`, supports one-shot and incremental
use, and verifies in constant time.

```swift
let webhookKey = SymmetricKey(size: .bits256)
let body = Data(#"{"event":"invoice.paid"}"#.utf8)

let tag = HMAC<SHA256>.authenticationCode(for: body, using: webhookKey)
let tagBytes = Data(tag)

let authentic = HMAC<SHA256>.isValidAuthenticationCode(
    tagBytes, authenticating: body, using: webhookKey
)
```

Verification must go through `isValidAuthenticationCode(_:authenticating:using:)`,
which compares safely in constant time. Never compare MAC bytes with `==` on `Data`.

`HMAC<SHA256>.MAC` is a typealias for `HashedAuthenticationCode<SHA256>`, which is
`ContiguousBytes`, `Sequence`, `Hashable` and `CustomStringConvertible`.

Typical uses: signing API requests, verifying webhooks, integrity of data in transit,
token schemes. HMAC proves who produced the data and that it was not changed; it
does not hide the data.

## AES-GCM

AES-GCM is the cipher to use by default. It is an AEAD mode: one `seal()` call gives
confidentiality, integrity and authenticity, replacing the old AES-CBC plus
separate HMAC construction.

```swift
let vaultKey = SymmetricKey(size: .bits256)
let note = Data("door code 4411".utf8)

let box = try AES.GCM.seal(note, using: vaultKey)
guard let stored = box.combined else { throw CryptoKitError.incorrectParameterSize }

let reopened = try AES.GCM.SealedBox(combined: stored)
let recovered = try AES.GCM.open(reopened, using: vaultKey)
```

`seal` picks a fresh random 12-byte nonce when you do not pass one. A sealed box
holds three parts: the 12-byte nonce, ciphertext of the same length as the
plaintext, and a 16-byte tag. `combined` lays them out as nonce, ciphertext, tag.

`AES.GCM.SealedBox.combined` is `Data?`: it is nil when the box was built with a
non-standard nonce length. `ChaChaPoly.SealedBox.combined` is not optional.

### Additional authenticated data

Pass context that must match on decryption but need not be secret:

```swift
let context = Data("owner=81923|doc=receipt-77|v=2".utf8)
let bound = try AES.GCM.seal(note, using: vaultKey, authenticating: context)
let plain = try AES.GCM.open(bound, using: vaultKey, authenticating: context)
```

AAD is authenticated but not encrypted. Binding a user id, resource id, version or
timestamp stops an attacker from moving a valid ciphertext into another record. A
mismatch makes `open` throw `CryptoKitError.authenticationFailure`.

### Nonce reuse

This is the classic mistake:

```swift
// Broken: the same fixed nonce for every message
let fixedNonce = try AES.GCM.Nonce(data: Data(count: 12))
let first = try AES.GCM.seal(Data("alpha".utf8), using: vaultKey, nonce: fixedNonce)
let second = try AES.GCM.seal(Data("bravo".utf8), using: vaultKey, nonce: fixedNonce)
```

Two messages under one key and one nonce share a keystream, so XOR of the
ciphertexts equals XOR of the plaintexts. Worse, the authentication subkey
H = AES_k(0^128) can be recovered by root finding (Cantor-Zassenhaus), after which
tags can be forged for any message. This is the "forbidden attack" described by
Joux in 2006, and a 2016 USENIX WOOT study found 184 HTTPS servers, some at
financial institutions, reusing GCM nonces in the wild.

The fix is to omit `nonce:`. With random 12-byte nonces the chance of any
collision stays below 2^-32 after 2^32 messages under one key. Supply an explicit
nonce only when an external protocol defines it, and then follow that protocol's
counter rules exactly.

## ChaChaPoly

ChaCha20-Poly1305 gives the same AEAD guarantees with the same API shape; switching
is a type-name change.

```swift
let sealed = try ChaChaPoly.seal(note, using: vaultKey)
let wire = sealed.combined
let parsed = try ChaChaPoly.SealedBox(combined: wire)
let opened = try ChaChaPoly.open(parsed, using: vaultKey)
```

Every Apple chip since A7, and every M-series chip, has AES instructions. Published
2025 benchmarks on an M2 Pro (OpenSSL) put AES-256-GCM at roughly 3-4 GB/s and
ChaChaPoly at roughly 1.5-2 GB/s, AES being 134% to 236% faster depending on size.
Apple's own keychain, file Data Protection and Watch-to-iPhone links all use AES.

So: AES-GCM on Apple hardware. Choose ChaChaPoly when there is no hardware AES,
when you need guaranteed constant-time software (no table lookups, no cache-timing
side channel), or when a protocol such as WireGuard or a ChaCha20 TLS suite
specifies it.

Neither cipher streams. For large files, either split into chunks with a unique
nonce per chunk and the chunk index (monotonic) in the AAD so chunks cannot be
reordered or dropped silently, or lean on file Data Protection, which the hardware
engine applies with AES-XTS.

## SymmetricKey

`SymmetricKey` zeroes its memory when deallocated (WWDC 2019 session 709), exposes
no `Data` property (only `withUnsafeBytes`), and validates its size.

`SymmetricKey(size: .bits256)` is 32 random bytes; `.bits128` and `.bits192` also
exist. Use 256 bits: Grover's algorithm halves effective strength, leaving AES-256
at 128 bits but AES-128 at 64 bits, which is not enough.

### Passwords are not keys

```swift
// Broken: a password is low-entropy, unsalted and free to guess
let weak = SymmetricKey(data: Data("summer2026".utf8))
```

A human password carries around 20-40 bits of entropy, and this has no salt and no
work factor. CryptoKit provides HKDF but not PBKDF2, so stretch the password with
CommonCrypto first, then optionally split it with HKDF:

```swift
import CommonCrypto

func stretch(passphrase: String, salt: Data, rounds: UInt32 = 600_000) -> SymmetricKey? {
    let secret = Array(passphrase.utf8)
    var output = [UInt8](repeating: 0, count: 32)
    let status = salt.withUnsafeBytes { saltBytes in
        CCKeyDerivationPBKDF(
            CCPBKDFAlgorithm(kCCPBKDF2),
            secret.map { Int8(bitPattern: $0) }, secret.count,
            saltBytes.bindMemory(to: UInt8.self).baseAddress, salt.count,
            CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256), rounds,
            &output, output.count
        )
    }
    guard status == kCCSuccess else { return nil }
    return SymmetricKey(data: output)
}

struct PasswordKeys {
    let salt: Data
    let encryption: SymmetricKey
    let authentication: SymmetricKey
}

func passwordKeys(for passphrase: String) -> PasswordKeys? {
    var saltBytes = [UInt8](repeating: 0, count: 32)
    guard SecRandomCopyBytes(kSecRandomDefault, saltBytes.count, &saltBytes) == errSecSuccess else { return nil }
    let salt = Data(saltBytes)
    guard let master = stretch(passphrase: passphrase, salt: salt) else { return nil }
    return PasswordKeys(
        salt: salt,
        encryption: HKDF<SHA256>.deriveKey(
            inputKeyMaterial: master, info: Data("encryption".utf8), outputByteCount: 32
        ),
        authentication: HKDF<SHA256>.deriveKey(
            inputKeyMaterial: master, info: Data("authentication".utf8), outputByteCount: 32
        )
    )
}
```

Keep the salt with the ciphertext: it is not secret, and deriving the same keys
again later needs it.

The OWASP Password Storage Cheat Sheet sets 600,000 PBKDF2-HMAC-SHA256 iterations
as the minimum; go lower only for a documented legacy interop requirement. Salts
must be random and at least 16 bytes (32 above).

For random bytes, `SecRandomCopyBytes` and `SymmetricKey(size:)` are the APIs to
use. On Apple platforms `arc4random_buf` and `SystemRandomNumberGenerator` also draw
from the kernel CSPRNG and are cryptographically secure, so they are not a
vulnerability; still prefer the Security and CryptoKit calls for key material so the
intent is explicit and the status is checked. What is never acceptable is a seeded
or non-cryptographic generator (`rand()`, `random()`, `srand48`, a custom LCG) or
`arc4random() % n` where modulo bias matters (use `arc4random_uniform`).

### HKDF

HKDF (RFC 5869) expands high-entropy input into subkeys. It adds no work factor, so
it is never enough on its own for a password.

```swift
let rootKey = SymmetricKey(size: .bits256)
let sessionKey = HKDF<SHA256>.deriveKey(
    inputKeyMaterial: rootKey,
    salt: Data("session-salt-01".utf8),
    info: Data("chat-session/aes".utf8),
    outputByteCount: 32
)
```

Use one-shot `deriveKey` or the two-step `extract` then `expand`. Give each subkey
its own `info` string for domain separation. The standalone `HKDF` type is iOS 14+.
`deriveKey` does not throw, so there is no `try`.

### Where keys live

```swift
// Broken: extractable from the binary with `strings`
let embedded = SymmetricKey(data: Data(base64Encoded: "q83vEjRWeJq8...")!)
```

A 2025 industry study found hardcoded secrets in 48% of mobile apps, and any
disassembler recovers them from the shipped binary. Keys instead come from one of:
the Keychain with `kSecAttrAccessibleWhenUnlockedThisDeviceOnly`, derivation from
something the user knows, or a secure server.

A `SymmetricKey` lives in process memory. It is not in the Secure Enclave; only the
asymmetric `SecureEnclave.P256` (and on iOS 26 the post-quantum SE types) are
hardware-backed (see [secure-enclave.md](secure-enclave.md)). Persist symmetric keys
only in the Keychain, never in UserDefaults or plain files
(see [credential-storage-patterns.md](credential-storage-patterns.md)).

## Moving off CommonCrypto

CommonCrypto means manual buffers, unsafe pointers and no authenticated encryption.

| CommonCrypto | CryptoKit |
| --- | --- |
| `CC_SHA256` with `withUnsafeBytes` and `CC_SHA256_DIGEST_LENGTH` | `SHA256.hash(data:)` |
| `CCCrypt` AES-CBC, `kCCOptionPKCS7Padding`, `kCCKeySizeAES256`, manual IV, output buffer sized with `kCCBlockSizeAES128` | `AES.GCM.seal(_:using:)` |
| `CCHmac(kCCHmacAlgSHA256, ...)` | `HMAC<SHA256>.authenticationCode` and `isValidAuthenticationCode` |

CBC without encrypt-then-MAC is exposed to padding-oracle attacks and accepts
tampered ciphertext silently. GCM's `open` throws
`CryptoKitError.authenticationFailure` if any byte changed.

Keep CommonCrypto only for PBKDF2 (`CCKeyDerivationPBKDF`), interop with an existing
AES-CBC format, and AES-ECB, which is almost never the right choice.

## Frequent mistakes

1. Writing CommonCrypto for new code when the target is iOS 13+.
2. Fixed, zero-filled or reused nonces. Leave `nonce:` out.
3. AES-CBC with no MAC.
4. Turning a password straight into a `SymmetricKey`. Use PBKDF2 with at least
   600,000 iterations, then HKDF if subkeys are needed.
5. MD5 or SHA-1 "just for a checksum". SHA-256 is just as fast in practice.
6. Hand-concatenating nonce, ciphertext and tag. Use `SealedBox.combined` and
   `SealedBox(combined:)`.

## Post-quantum outlook

WWDC 2025 session 314 introduced ML-KEM and ML-DSA for the asymmetric side (see
[cryptokit-public-key.md](cryptokit-public-key.md)). Symmetric primitives survive a
quantum adversary with roughly half their bit strength, so use
`SymmetricKey(size: .bits256)` and nothing smaller. iOS 26 also turns on
quantum-secure TLS 1.3 key exchange by default for `URLSession` and
Network.framework.

Under the hood CryptoKit calls corecrypto, which carries FIPS 140-2 / 140-3
validation and hand-tuned assembly per CPU microarchitecture, and the hardware
engine in the storage DMA path encrypts with AES-256 inline at line speed.

## OWASP mapping

This material addresses OWASP Mobile Top 10 (2024) M10, Insufficient Cryptography.

- MASTG tests: MASTG-TEST-0061 (algorithm configuration), 0062 (key management),
  0209 (key sizes), 0210 (broken symmetric algorithms), 0211 (broken hashing),
  0213 (hardcoded keys), 0317 (broken modes).
- MASTG knowledge: MASTG-KNOW-0066 (CryptoKit), MASTG-KNOW-0067 (CommonCrypto).
- MASWE: 0010 (key derivation), 0013 (hardcoded keys), 0020 (improper encryption),
  0021 (improper hashing), 0022 (predictable IVs).

See also [common-anti-patterns.md](common-anti-patterns.md) (#6 nonce reuse, #7 weak
hashes) and [compliance-owasp-mapping.md](compliance-owasp-mapping.md).

## Tests worth writing

- Flip one ciphertext byte; `open` throws `CryptoKitError.authenticationFailure`.
- Open with different AAD; same error.
- HMAC checked with the wrong key returns false.
- HMAC over a modified message returns false.
- Below iOS 26 the SHA-3 path falls back to SHA-256.
- A `combined` round trip returns the original plaintext.
- PBKDF2 plus HKDF is deterministic: same password and salt give the same key.

CI should flag `Insecure.MD5`, `Insecure.SHA1`, `CCCrypt`, `SymmetricKey(data:` fed
from a string literal, and base64 blobs that look like embedded keys.

## Sources

WWDC 2019 session 709 (Cryptography and Your Apps); WWDC 2020 "What's New in
CryptoKit" (HKDF, iOS 14); WWDC 2025 session 314; the CryptoKit documentation; Apple
Platform Security Guide; OWASP Mobile Top 10 (2024) M10; OWASP MASTG; RFC 5869;
Joux 2006 on GCM nonce reuse.

## Checklist

- [ ] CryptoKit everywhere except PBKDF2.
- [ ] Nothing weaker than SHA-256; CI flags MD5 and SHA-1.
- [ ] Only AEAD (AES-GCM or ChaChaPoly); no unauthenticated CBC.
- [ ] `nonce:` omitted unless a protocol dictates it; never static or zero.
- [ ] 256-bit keys; no `.bits128` for sensitive data.
- [ ] Passwords: `CCKeyDerivationPBKDF` with at least 600,000 iterations and a random
      salt of 16 bytes or more, then HKDF if needed.
- [ ] Serialization through `.combined` and `SealedBox(combined:)`.
- [ ] Keys in the Keychain as WhenUnlockedThisDeviceOnly; never in source,
      UserDefaults or a plist.
- [ ] MACs verified with `HMAC.isValidAuthenticationCode()`.
- [ ] `SHA3_256` behind `#available(iOS 26.0, macOS 26.0, *)` with a SHA-256 fallback.
- [ ] Metadata (user id, resource id, version) bound through `authenticating:`.
