Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Password Hashing Implementation in Swift

14 min readintermediate
Website QA and SEO audits

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 stores a login credential as a deliberately slow, salted, one-way derivation instead of the password itself. You verify by re-deriving with the stored salt and parameters and comparing in constant time. The cost parameters (iterations, memory, parallelism) exist to make offline cracking of a stolen table expensive. The modern choices are Argon2id, scrypt, bcrypt and PBKDF2 with a high iteration count. A plain SHA-256 or MD5 digest is not password hashing: a GPU computes billions of those per second. You reach for this the moment you own a users table with a password column, and again every few years when you raise the cost and rehash on next login.

Password Hashing in Swift: what you actually reach for

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.

Swift implementation

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. Rounds should be chosen with CCCalibratePBKDF for the slowest supported device rather than hardcoded from a Mac measurement. The CCCryptorStatus is converted into a thrown Swift error, never discarded, and the derivation never runs on the main actor.
swift
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 Free

The Swift-specific trap

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.

Performance in Swift, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Password Hashing between languages.

Real-World Applications

Password Hashing is used extensively in production software: authentication systems, payment processing, encrypted communications, and data protection mechanisms depend on this technique. In Swift, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Password Hashing helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Password Hashing appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Password Hashing over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Password Hashing to build pattern recognition. In Swift, demonstrate proficiency with optionals and value types to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Swift code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.