Password Hashing Implementation in Swift
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Password Hashing runs in O(n) time and O(1) space, in Swift as in every other language.
- ✓CryptoKit has no password hashing at all: it offers SHA-2, HMAC and HKDF, and HKDF is a key-derivation function for high-entropy secrets, not a password KDF.
- ✓A reviewer rejects SHA256.hash(data:) or HKDF over a password outright. Byte lengths passed into the C API must come from the UTF-8 view, and the pointer handed to CCKeyDerivationPBKDF must not escape the withUnsafeBytes closure.
- ✓The Swift trap: String.count is a count of grapheme clusters, not bytes, and CCKeyDerivationPBKDF wants a byte length.
- ✓CommonCrypto's PBKDF2 is the platform's optimised implementation, so it is far faster per round than an equivalent Swift loop; ARC retain and release traffic around the wrapper is noise beside 200,000 HMAC rounds.
What Password Hashing actually is
Password Hashing in Swift: what you actually reach for
Swift implementation
import CommonCrypto
import Foundation
enum PasswordKDF {
enum KDFError: Error {
case commonCrypto(CCCryptorStatus)
}
static func derive(password: String,
salt: Data,
rounds: UInt32 = 600_000,
length: Int = 32) throws -> Data {
let normalized = password.precomposedStringWithCanonicalMapping
let pw = Array(normalized.utf8).map { Int8(bitPattern: $0) }
var derived = [UInt8](repeating: 0, count: length)
let status = salt.withUnsafeBytes { saltBuf -> Int32 in
CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
pw, pw.count,
saltBuf.bindMemory(to: UInt8.self).baseAddress, salt.count,
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256),
rounds,
&derived, derived.count)
}
guard status == Int32(kCCSuccess) else {
throw KDFError.commonCrypto(CCCryptorStatus(status))
}
return Data(derived)
}
static func constantTimeEquals(_ a: Data, _ b: Data) -> Bool {
guard a.count == b.count else { return false }
var diff: UInt8 = 0
for (x, y) in zip(a, b) { diff |= x ^ y }
return diff == 0
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Swift-specific trap
Performance in Swift, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Swift type or library should I use for Password Hashing?
CryptoKit has no password hashing at all: it offers SHA-2, HMAC and HKDF, and HKDF is a key-derivation function for high-entropy secrets, not a password KDF. On Apple platforms the password KDF is CommonCrypto's CCKeyDerivationPBKDF, reached with import CommonCrypto, together with CCCalibratePBKDF which reports how many rounds hit a target millisecond budget on this device. apple/swift-crypto mirrors CryptoKit on Linux and likewise has no Argon2 or bcrypt, so server-side Swift reaches for Vapor's Bcrypt type (Bcrypt.hash and Bcrypt.verify) or a C-interop Argon2 package. swift-crypto does ship PBKDF2 in its _CryptoExtras module as KDF.Insecure.PBKDF2.deriveKey(from:salt:using:outputByteCount:rounds:), which is the portable option; CommonCrypto in the sample below is Apple-platforms-only.
What is the most common Swift mistake when implementing Password Hashing?
String.count is a count of grapheme clusters, not bytes, and CCKeyDerivationPBKDF wants a byte length. Passing password.count for a password containing an accented character, an emoji or a family sequence hashes only a prefix of the UTF-8, silently discarding entropy, and no test fails because hashing and verification truncate identically. Take Array(password.utf8) and pass that array's count. Related and Swift-specific: String has no canonical byte form, so the same characters entered on two Apple platforms can arrive decomposed on one and precomposed on the other. Pick one normalisation form and use the identical form on every client writing to the same user table: NFC via precomposedStringWithCanonicalMapping, or NFKC via precomposedStringWithCompatibilityMapping, which is the form the JavaScript and C# code on this page applies.
How does Password Hashing actually perform in Swift?
CommonCrypto's PBKDF2 is the platform's optimised implementation, so it is far faster per round than an equivalent Swift loop; ARC retain and release traffic around the wrapper is noise beside 200,000 HMAC rounds. What does cost you is bridging: Data backed by a foreign or discontiguous buffer copies when you take unsafe bytes, and converting to and from [UInt8] allocates again. Device spread is the real caveat: rounds calibrated on an M-series Mac are weak on a phone, which is what CCCalibratePBKDF exists to solve. Run it off the main thread or the UI freezes. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.