Skip to content
Tutorials Center
My learning

Topics

Lesson 131 of 146 ยท Platforms and Ecosystem

Security: Keychain, CryptoKit and Safe Parsing

Learn secure habits in Swift - storing secrets in the Keychain, hashing and encryption with CryptoKit, constant-time comparison, and parsing untrusted input safely.

Most security bugs are not clever attacks on cryptography. They are ordinary mistakes: a password written to a log, an API key committed next to the code, a length field that is trusted, a string compared in a way that leaks timing. Swift helps with some of this for free (memory safety, no buffer overruns in safe code, overflow traps), but the rest is up to you.

This lesson covers three areas. Storing secrets on Apple platforms with the Keychain. Hashing and encryption with CryptoKit, plus a hand-written hash so you can see what a hash is. Safe parsing: treating every byte that comes from outside as untrusted. The Keychain and CryptoKit are Apple frameworks that do not exist on this site's Linux runner, so their code is shown read-only. Everything in the runnable examples is plain Swift.

Never invent your own cryptography for real products. The hand-written code in this lesson exists to teach ideas and is not safe to use for passwords or secrets. In production use CryptoKit, swift-crypto or the platform's password APIs.

Where secrets belong

flowchart TD
    A["Where do I put it?"] --> B{"Is it a secret?<br/>(password, token, key)"}
    B -- "no" --> C["UserDefaults, a file, the database"]
    B -- "yes" --> D{"Must the app read it back?"}
    D -- "no (verify only)" --> E["Store a salted slow hash,<br/>never the secret"]
    D -- "yes" --> F["Keychain"]

Secrets the app must read again go in the Keychain; secrets it only needs to verify should not be stored at all, only their hash.

Do not keep secrets in UserDefaults, in Info.plist, in source files or in logs. All of those are readable from a device backup, from a decompiled app or from a crash report. The only place Apple designs for secrets is the Keychain, an encrypted database managed by the operating system and protected by the device passcode and the Secure Enclave.

The Keychain (read-only)

The Keychain API is a C-style interface built from dictionaries. You describe an item, and call SecItemAdd, SecItemCopyMatching, SecItemUpdate or SecItemDelete.

Swift
// Apple platforms only - read-only example
import Security
import Foundation

enum KeychainError: Error { case unexpectedStatus(OSStatus), notFound }

struct TokenStore {
    let service = "com.example.myapp"

    func save(token: String, account: String) throws {
        let data = Data(token.utf8)
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
            kSecValueData as String: data,
            kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
        ]
        SecItemDelete(query as CFDictionary)             // replace an old value
        let status = SecItemAdd(query as CFDictionary, nil)
        guard status == errSecSuccess else { throw KeychainError.unexpectedStatus(status) }
    }

    func load(account: String) throws -> String {
        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
            kSecReturnData as String: true,
            kSecMatchLimit as String: kSecMatchLimitOne
        ]
        var item: CFTypeRef?
        let status = SecItemCopyMatching(query as CFDictionary, &item)
        if status == errSecItemNotFound { throw KeychainError.notFound }
        guard status == errSecSuccess, let data = item as? Data,
              let token = String(data: data, encoding: .utf8) else {
            throw KeychainError.unexpectedStatus(status)
        }
        return token
    }
}

The points to remember:

  • An item is identified by its class (here kSecClassGenericPassword) plus attributes such as service and account. Adding an item that already exists fails with errSecDuplicateItem, so delete first or use SecItemUpdate.
  • kSecAttrAccessible controls when the secret can be read. WhenUnlockedThisDeviceOnly means: only while the device is unlocked, and never copied to another device through a backup. Use the strictest option that your feature allows.
  • Every call returns an OSStatus. Check it; ignoring it is how apps silently lose their tokens.
  • Wrap the API in one small type like TokenStore, so the rest of the app never sees dictionaries and so tests can replace it with a fake behind a protocol (see App Architecture).

On Linux, Windows and servers there is no Keychain. Use the platform's secret manager or environment variables supplied at deploy time (see Processes and environment), and never commit them.

Hashing: a fingerprint of data

A cryptographic hash turns any amount of data into a fixed-size fingerprint. The same input always gives the same output, a tiny change gives a completely different result, and you cannot work backwards from the fingerprint to the input. SHA-256 outputs 32 bytes, usually shown as 64 hex digits.

Hashes are for integrity (has this file changed?), identifiers (cache keys) and building blocks of other schemes. With CryptoKit:

Swift
// Apple platforms only - read-only example
import CryptoKit
import Foundation

let digest = SHA256.hash(data: Data("hello".utf8))
let hex = digest.map { String(format: "%02x", $0) }.joined()
print(hex)

To see that there is no magic, the next example implements SHA-256 in plain Swift. It follows the published algorithm: pad the message, process it in 64-byte blocks, and mix eight 32-bit words with bit rotations. You do not need to memorize it; notice the helper that rotates bits and the &+ operators that wrap around on overflow (see bitwise and overflow operators).

Swift SHA-256 from scratch (for learning only)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The first line is the well-known SHA-256 of abc, and it begins ba7816bf. Changing a single letter (abd) produces a completely unrelated result: this is the avalanche effect. The third line is the hash of empty input.

Hashing is not password storage

A plain SHA-256 is fast, which is exactly wrong for passwords: an attacker with a stolen database can test billions of guesses per second. Passwords need a slow, salted scheme (bcrypt, scrypt, Argon2 or PBKDF2). A salt is random data stored next to the hash so identical passwords hash differently and precomputed tables are useless. The best design is to let a dedicated identity provider (or the platform's "Sign in with ..." and passkeys) handle passwords so your app never stores them at all.

Comparing secrets safely

When you compare a computed value with a stored one (a token, a MAC), a normal == can return as soon as it finds the first difference. An attacker who can measure response times learns how many leading bytes were right. A constant-time comparison always looks at every byte.

Swift Constant-time comparison and a salted, iterated hash

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The comparison loop accumulates differences with bitwise OR and decides only at the end. The toyDerive function only shows the shape of password hashing: a per-user salt and many rounds, so each guess costs the attacker real work. Its mixing step is a made-up stand-in; never ship it.

With CryptoKit you would use HMAC<SHA256>.isValidAuthenticationCode(_:authenticating:using:), which does the comparison in constant time for you.

Encryption with CryptoKit (read-only)

Hashing is one way. Encryption is reversible with a key. CryptoKit offers authenticated encryption, which both hides the data and detects tampering, so a modified message fails to decrypt instead of silently decrypting to garbage.

Swift
// Apple platforms only - read-only example
import CryptoKit
import Foundation

let key = SymmetricKey(size: .bits256)               // random, from the system generator
let secret = Data("meet at noon".utf8)

let sealed = try AES.GCM.seal(secret, using: key)    // random nonce is chosen for you
let combined = sealed.combined!                      // nonce + ciphertext + tag, safe to store

let box = try AES.GCM.SealedBox(combined: combined)
let opened = try AES.GCM.open(box, using: key)       // throws if the data was altered
print(String(decoding: opened, as: UTF8.self))

Rules that keep this safe:

  • Let the library generate keys and nonces. Never reuse a nonce with the same key in AES-GCM.
  • Keep the key in the Keychain (or derive it from a user secret with a key-derivation function), not in the source.
  • Use authenticated modes (AES.GCM, ChaChaPoly) and check the thrown errors.
  • Use SystemRandomNumberGenerator, which Swift's random(in:) uses by default and which is cryptographically secure, when you need unpredictable bytes. Seeded generators (see random and seeding) are for reproducible tests, never for secrets.

Safe parsing of untrusted input

Everything that crosses your boundary (a file, a network message, a command-line argument, a deep-link URL) is untrusted until you have checked it. Swift's type system already prevents many classic bugs, but logic errors remain. The habit is: validate early, with limits, into a typed value, and reject anything else.

Swift Validating untrusted input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Each step has a reason:

  1. Cap the size first. A huge input should be rejected before you split, copy or decode it.
  2. Use an allow-list. The name check rejects the path-traversal attempt ../../etc/passwd because / is not allowed; the explicit .. and leading-dot checks guard names that look harmless.
  3. Int(_:) returns nil on overflow, so the 20-digit size is rejected instead of wrapping. In arithmetic use addingReportingOverflow or multipliedReportingOverflow when values come from outside; plain + traps (crashes) on overflow, which is safe but is a denial of service if an attacker triggers it.
  4. Bound counts and nesting. A JSON document with a million nested arrays can exhaust memory or the stack. Decode with limits you choose and reject deeper input. See JSON and Codable.

A few more habits:

  • Do not use !, try! or array indexing on untrusted data; use guard let and safe subscripts so bad input becomes an error, not a crash.
  • Never build SQL, shell commands or file paths by pasting strings. Use parameterized queries and pass command arguments as an array.
  • Do not log secrets. Redact tokens and passwords in description and in logs (see logging).
  • Use HTTPS and keep App Transport Security on. Pin certificates only when you can also rotate them.
  • Keep dependencies updated; most real incidents come from old libraries.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should an app that must read a login token back store it on an Apple platform?

    The Keychain is the OS-managed encrypted store for secrets. The other places are readable from backups or the app bundle.
  2. 2. Why is a plain SHA-256 a poor way to store passwords?

    Password storage should use bcrypt, scrypt, Argon2 or PBKDF2 with a per-user salt.
  3. 3. What is the purpose of a constant-time comparison?

    An ordinary == stops at the first difference. Looking at every byte hides that information.
  4. 4. What does Int("99999999999999999999") return?

    The failable initializer returns nil when the text is not a valid in-range Int, so overflow becomes an error you handle.
  5. 5. Which is the safest approach to validating a file name from user input?

    An allow-list is smaller and safer than trying to list everything dangerous.

Summary

  • Secrets belong in the Keychain on Apple platforms (with the strictest accessibility option), never in defaults, source, logs or the app bundle.
  • A cryptographic hash is a one-way fingerprint for integrity; passwords need slow, salted schemes or an identity provider.
  • Use CryptoKit's authenticated encryption (AES.GCM, ChaChaPoly), let it pick nonces, and keep keys in the Keychain.
  • Compare secrets in constant time (HMAC.isValidAuthenticationCode does it for you).
  • Treat all external data as untrusted: cap size, allow-list characters, parse numbers with bounds, limit collections and depth.
  • Avoid !, try! and raw indexing on outside data, and never build SQL, shell commands or paths by string concatenation.
  • Do not write your own cryptography for production use.

Next: Project: Calculator