0Pricing
Swift Academy · Lesson

Data Protection and Encryption

Protect files and use CryptoKit basics.

Data Protection and Encryption is a free Swift Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Data Protection on iOS

iOS encrypts files on disk by default, but you can choose when a file's contents are decryptable using Data Protection classes. These tie file access to the device lock state, much like Keychain accessibility classes do for secrets.

import Foundation
// File-level protection ties decryption to lock state.
// Set a protection class when writing sensitive files.

The Protection Classes

The main file protection levels are .complete (unreadable while locked), .completeUnlessOpen (stays readable if already open when locked), .completeUntilFirstUserAuthentication (readable after first unlock), and .none.

import Foundation
// FileProtectionType:
//   .complete
//   .completeUnlessOpen
//   .completeUntilFirstUserAuthentication (default)
//   .none
let level = FileProtectionType.complete
_ = level

Writing a Protected File

Pass .completeFileProtection in the write options to mark a file as fully protected. While the device is locked, the OS makes its contents inaccessible even to your own app.

import Foundation
func writeSecure(_ data: Data, to url: URL) throws {
    try data.write(
        to: url,
        options: [.completeFileProtection])
}

Setting Protection on Existing Files

You can change a file's protection after creation by setting the FileAttributeKey.protectionKey attribute via FileManager. This is handy for tightening protection on files you receive or migrate.

import Foundation
func protect(_ url: URL) throws {
    try FileManager.default.setAttributes(
        [.protectionKey: FileProtectionType.complete],
        ofItemAtPath: url.path)
}

CryptoKit for In-App Encryption

When you need to encrypt data yourself — before uploading, or to add a layer on top of disk protection — use CryptoKit. It provides modern, misuse-resistant primitives with safe defaults and no manual IV juggling for AEAD ciphers.

import CryptoKit
// CryptoKit offers hashing, symmetric & public-key
// crypto with safe, hard-to-misuse APIs.

Hashing With SHA-256

For integrity checks and fingerprints, SHA256 produces a fixed-size digest. Note hashing is one-way and not a substitute for encryption — never hash a password without a salt and a slow KDF.

import CryptoKit
import Foundation
func fingerprint(_ data: Data) -> String {
    let digest = SHA256.hash(data: data)
    return digest.map { String(format: "%02x", $0) }
        .joined()
}

Symmetric Keys

Symmetric encryption uses one shared key. SymmetricKey(size: .bits256) generates a strong random key. Store the key in the Keychain — never alongside the ciphertext it protects.

import CryptoKit
let key = SymmetricKey(size: .bits256)
// Persist this key in the Keychain, not in a file.
_ = key

Encrypting With AES-GCM

AES.GCM is authenticated encryption: it both encrypts and detects tampering. seal returns a sealed box containing the ciphertext, nonce, and authentication tag bundled together.

import CryptoKit
import Foundation
func encrypt(_ data: Data, key: SymmetricKey)
    throws -> Data {
    let sealed = try AES.GCM.seal(data, using: key)
    return sealed.combined! // nonce + ciphertext + tag
}

Decrypting and Verifying

To decrypt, reconstruct a SealedBox from the combined data and call open. If the ciphertext or tag was altered, open throws — the authentication tag guarantees integrity, so corrupted data never decrypts silently.

import CryptoKit
import Foundation
func decrypt(_ combined: Data, key: SymmetricKey)
    throws -> Data {
    let box = try AES.GCM.SealedBox(combined: combined)
    return try AES.GCM.open(box, using: key)
}

Deriving Keys From Passwords

Never use a raw password as a key. Derive one with HKDF (for high-entropy inputs) or a password-based KDF. CryptoKit's HKDF stretches and salts key material into a proper symmetric key.

import CryptoKit
import Foundation
func deriveKey(from secret: Data, salt: Data)
    -> SymmetricKey {
    return HKDF<SHA256>.deriveKey(
        inputKeyMaterial: SymmetricKey(data: secret),
        salt: salt,
        outputByteCount: 32)
}

Layering the Defenses

Strong apps combine layers: Data Protection encrypts files at rest tied to lock state, the Keychain guards keys behind biometrics, and CryptoKit adds app-level encryption for data in transit or in the cloud. Each layer fails safely on its own.

import CryptoKit
import Foundation
// 1. Key lives in Keychain (biometric-gated)
// 2. Plaintext file written with .completeFileProtection
// 3. Uploads encrypted with AES.GCM before leaving device
let layers = "defense in depth"
_ = layers

Quick Check

Recall why AES-GCM is preferred for app-level encryption.

Recap

You learned data protection and encryption:

  • File Data Protection classes (.complete, .completeUntilFirstUserAuthentication) tie disk decryption to lock state.
  • CryptoKit provides SHA-256 hashing, SymmetricKey generation, and AES-GCM authenticated encryption via seal/open.
  • Derive keys with HKDF; store keys in the Keychain, never beside the ciphertext.
  • Layer Data Protection, Keychain, and CryptoKit for defense in depth.

Frequently asked questions

Is the “Data Protection and Encryption” lesson free?

Yes — the full text of “Data Protection and Encryption” is free to read here on the web, and the Swift Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Data Protection and Encryption”?

Protect files and use CryptoKit basics. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Data Protection and Encryption” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Storing Secrets in the Keychain
  2. Keychain Access Control
  3. Biometric Authentication
  4. Data Protection and Encryption
← Back to Swift Academy