Complete CryptoKit Guide: iOS Cryptography Fundamentals

Published on Β· 48 min

Wlad
Wlad
Founder & CEO

Data security has never been more critical than today. Between high-profile data breaches, strict GDPR regulations, and growing user expectations, mastering cryptography has become essential for every professional iOS developer. CryptoKit, introduced with iOS 13, revolutionizes the approach to cryptography on Apple platforms by offering a Swift-native, type-safe, and hardware-accelerated API.

🎯 Why Cryptography?

Modern cryptography addresses three fundamental needs in computer security:

Confidentiality β€” Only authorized parties can read the data. Encryption transforms readable information into incomprehensible data without the appropriate key.

Integrity β€” Data has not been altered. Hash functions detect any modification, even minimal ones.

Authentication β€” The sender's identity is verifiable. Digital signatures guarantee the origin of data and non-repudiation.

The Evolution of Cryptography on iOS

Before CryptoKit, iOS developers navigated a fragmented landscape. CommonCrypto, inherited from the C era, offered performance but a complex and error-prone API. The Security Framework provided Keychain integration but lacked consistency. CryptoKit unifies these approaches into a modern API that leverages Swift and Apple chip hardware acceleration.

FrameworkLanguageType-SafetyHardware AccelerationAvailability

CommonCrypto

C

No

Limited

iOS 2+

Security Framework

C/Obj-C

Partial

Yes

iOS 2+

CryptoKit

Swift

Complete

Optimized

iOS 13+

CryptoKit's Strengths

CryptoKit stands out with several characteristics that make it the preferred choice for modern applications. Its declarative API drastically reduces boilerplate code while eliminating common memory manipulation errors. Native integration with the Secure Enclave allows protecting sensitive keys at the hardware level. Finally, algorithms are constantly updated by Apple to reflect cryptographic best practices.

πŸ” Hashing: Digital Fingerprints

Hashing is the cornerstone of cryptography. A hash function transforms data of arbitrary size into a fixed-size fingerprint, in a deterministic and irreversible manner.

Available SHA Functions

CryptoKit implements the SHA-2 family from NIST, considered the security standard:

Use Case: File Integrity Verification

Hashing finds practical application in verifying the integrity of downloaded or stored files:

HMAC: Hash-Based Authentication

HMAC (Hash-based Message Authentication Code) combines hashing with a secret key to authenticate both the origin and integrity of data:

πŸ”’ Symmetric Encryption

Symmetric encryption uses the same key to encrypt and decrypt data. CryptoKit offers two AEAD (Authenticated Encryption with Associated Data) algorithms that combine confidentiality and integrity.

AES-GCM vs ChaChaPoly

CharacteristicAES-GCMChaChaPoly

Standard

NIST

IETF

Performance (with AES-NI)

Excellent

Very good

Performance (without AES-NI)

Moderate

Excellent

Nonce size

96 bits

96 bits

Tag size

128 bits

128 bits

Recommendation

Servers, Apple Silicon

Mobile, IoT

Apple devices have AES hardware acceleration, so both algorithms offer comparable performance on iOS.

Symmetric Key Generation

Encryption / Decryption with AES-GCM

Encryption with ChaChaPoly

Anatomy of a Sealed Box

Understanding the internal structure of a Sealed Box is essential for interoperability:

πŸ”‘ Asymmetric Cryptography

Asymmetric cryptography uses a pair of mathematically linked keys: a public key (shareable) and a private key (secret). CryptoKit implements standardized elliptic curves and Curve25519.

Available Elliptic Curves

CurveKey SizeStandardRecommended Usage

P-256

256 bits

NIST

General, compatible

P-384

384 bits

NIST

High security

P-521

521 bits

NIST

Maximum security

Curve25519

256 bits

Bernstein

Modern, performant

Key Pair Generation

Key Agreement (ECDH)

Elliptic Curve Diffie-Hellman (ECDH) key exchange allows two parties to derive a shared secret over an insecure channel:

Key Derivation (HKDF)

HKDF (HMAC-based Key Derivation Function) transforms a shared secret into cryptographic keys of arbitrary size:

✍️ Digital Signatures

Digital signatures guarantee the authenticity and non-repudiation of data. CryptoKit supports ECDSA on NIST curves and Ed25519.

ECDSA with P-256

Ed25519: Modern Signatures

Ed25519 offers fast and compact signatures, based on Daniel J. Bernstein's work:

ECDSA vs Ed25519 Comparison

CharacteristicECDSA P-256Ed25519

Signature size

~70-72 bytes (DER)

64 bytes

Public key size

65 bytes (uncompressed)

32 bytes

Performance

Good

Excellent

Determinism

No (requires RNG)

Yes

Compatibility

TLS, X.509, WebAuthn

SSH, Signal, Blockchain

πŸ›‘οΈ Secure Enclave Integration

The Secure Enclave is an isolated cryptographic coprocessor present in Apple devices since the iPhone 5s. It allows generating and storing private keys that never leave the hardware enclave.

Keys in the Secure Enclave

Biometric Authentication + Cryptography

Combining Face ID/Touch ID with the Secure Enclave provides native two-factor authentication:

Secure Enclave Limitations

The Secure Enclave has certain constraints to consider:

LimitationDescriptionWorkaround

Supported curves

P-256 only

Use software P-256 for other curves

Data size

Signing only (no direct encryption)

Sign symmetric keys

Export

Private keys non-extractable

Use dataRepresentation for reference

Simulator

Not available

Test on real device

πŸ’Ό Practical Use Cases

Local Sensitive Data Encryption

Secure Client-Server Communication

Local JWT Signing

⚠️ Best Practices and Common Mistakes

Never Hardcode Keys

Cryptographic Error Handling

Key Rotation

Security Checklist

CheckDescriptionPriority

βœ… Randomly generated keys

Never derive keys from simple passwords

Critical

βœ… Keychain storage

Sensitive keys in Keychain, not UserDefaults

Critical

βœ… Secure Enclave

Signing/authentication keys in the enclave

High

βœ… Unique nonces

Never reuse a nonce with the same key

Critical

βœ… Error handling

Proper handling of crypto failures

High

βœ… Key rotation

Periodic rotation plan

Medium

βœ… Audit logging

Logging of sensitive operations

Medium

βœ… Regression tests

Automated tests for crypto functions

High

πŸš€ Going Further

CryptoKit forms the foundation of security on iOS, but Apple's ecosystem offers extended capabilities for the most demanding applications.

CryptoKit Quantum

For applications requiring protection against future quantum computer threats, CryptoKit now integrates post-quantum algorithms. Check out our dedicated article on quantum-secure workflows with ML-KEM and ML-DSA.

Official Resources

Apple Developer Documentation

Standards and Recommendations

Source Code

Next Steps

To deepen your mastery of security on iOS, explore the Security Framework for advanced Keychain integration, X.509 certificates, and network authentication. Combining CryptoKit with Local Authentication enables building robust multi-factor authentication flows leveraging Face ID and Touch ID.