From 3970ba6ac2c5a8e0daa38713a264d45d2131f41a Mon Sep 17 00:00:00 2001 From: Paul Toffoloni Date: Wed, 17 Dec 2025 15:44:32 +0100 Subject: [PATCH 1/5] Add PBKDF2 password hashing --- Package.swift | 3 +- .../Passwords/PBKDF2Hasher.swift | 180 ++++++++++++++++++ Tests/AuthenticationTests/PBKDF2Tests.swift | 124 ++++++++++++ 3 files changed, 306 insertions(+), 1 deletion(-) create mode 100644 Sources/Authentication/Passwords/PBKDF2Hasher.swift create mode 100644 Tests/AuthenticationTests/PBKDF2Tests.swift diff --git a/Package.swift b/Package.swift index 2641961..727564a 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let extraSettings: [SwiftSetting] = [ .enableUpcomingFeature("ExistentialAny"), .enableUpcomingFeature("MemberImportVisibility"), .enableUpcomingFeature("InternalImportsByDefault"), -// .treatAllWarnings(as: .error), + // .treatAllWarnings(as: .error), .strictMemorySafety(), .enableExperimentalFeature("SafeInteropWrappers"), .unsafeFlags(["-Xcc", "-fexperimental-bounds-safety-attributes"]), @@ -45,6 +45,7 @@ let package = Package( dependencies: [ .target(name: "CVaporAuthBcrypt"), .product(name: "Crypto", package: "swift-crypto"), + .product(name: "CryptoExtras", package: "swift-crypto"), ], swiftSettings: extraSettings ), diff --git a/Sources/Authentication/Passwords/PBKDF2Hasher.swift b/Sources/Authentication/Passwords/PBKDF2Hasher.swift new file mode 100644 index 0000000..90f3f44 --- /dev/null +++ b/Sources/Authentication/Passwords/PBKDF2Hasher.swift @@ -0,0 +1,180 @@ +public import CryptoExtras + +#if canImport(FoundationEssentials) +public import FoundationEssentials +#else +public import Foundation +#endif + +/// A password hasher using PBKDF2 with configurable hash function and iterations. +/// +/// The output format is a modular crypt format string: +/// `$pbkdf2-$$$` +/// +/// This format is compatible with passlib and other common PBKDF2 implementations. +/// See: https://passlib.readthedocs.io/en/stable/lib/passlib.hash.pbkdf2_digest.html +public struct PBKDF2Hasher: PasswordHasher { + let pseudoRandomFunction: KDF.Insecure.PBKDF2.HashFunction + let outputByteCount: Int + let iterations: Int + + /// Creates a PBKDF2 password hasher. + /// + /// - Parameters: + /// - pseudoRandomFunction: The hash function to use. Defaults to SHA-256. + /// - iterations: The number of PBKDF2 iterations. If nil, uses OWASP-recommended + /// defaults based on the hash function. + /// - Note: the parameters passed in here will only be used for hashing, verification + /// will rely solely on the parameters inside of the hash. + public init( + pseudoRandomFunction: KDF.Insecure.PBKDF2.HashFunction = .sha256, + iterations: Int? = nil + ) { + self.pseudoRandomFunction = pseudoRandomFunction + + // OWASP recommendations: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2 + let defaultIterations: Int = + switch pseudoRandomFunction { + case .sha256: 600_000 + case .sha384: 400_000 + case .sha512: 210_000 + case .insecureSHA1: 1_300_000 + case .insecureSHA224: 800_000 + case .insecureMD5: 1_600_000 + default: fatalError("Unsupported hash function") + } + self.iterations = iterations ?? defaultIterations + + self.outputByteCount = + switch pseudoRandomFunction { + case .sha256: 32 + case .sha384: 48 + case .sha512: 64 + case .insecureSHA224: 28 + case .insecureSHA1: 20 + case .insecureMD5: 16 + default: fatalError("Unsupported hash function") + } + } + + /// Hashes a password using PBKDF2. + /// + /// - Parameter password: The password to hash. + /// - Returns: The hash string as UTF-8 bytes. + public func hash(_ password: Password) throws -> [UInt8] where Password: DataProtocol { + let salt = [UInt8].random(count: 16) + let key = try KDF.Insecure.PBKDF2.deriveKey( + from: password, + salt: salt, + using: pseudoRandomFunction, + outputByteCount: outputByteCount, + unsafeUncheckedRounds: iterations + ) + + let keyData = unsafe key.withUnsafeBytes { unsafe Data($0) } + + // PHC format: $pbkdf2-$$$ + let algorithmId = Self.algorithmIdentifier(for: pseudoRandomFunction) + let b64Salt = Data(salt).base64EncodedString() + let b64Hash = keyData.base64EncodedString() + + let phcString = "$pbkdf2-\(algorithmId)$\(iterations)$\(b64Salt)$\(b64Hash)" + return Array(phcString.utf8) + } + + /// Verifies a password against a hash. + /// + /// - Parameters: + /// - password: The password to verify. + /// - digest: The stored hash. + /// - Returns: `true` if the password matches, `false` otherwise. + public func verify(_ password: Password, created digest: Digest) throws -> Bool + where Password: DataProtocol, Digest: DataProtocol { + guard !digest.isEmpty else { return false } + + let digestString = String(decoding: digest, as: UTF8.self) + guard let parsed = Self.parsePassword(digestString), parsed.algorithm == pseudoRandomFunction else { + return false + } + + let key = try KDF.Insecure.PBKDF2.deriveKey( + from: password, + salt: parsed.salt, + using: parsed.algorithm, + outputByteCount: parsed.hash.count, + unsafeUncheckedRounds: parsed.iterations + ) + + let keyData = unsafe key.withUnsafeBytes { unsafe Data($0) } + + return keyData.elementsEqual(parsed.hash) + } + + private struct ParsedPassword { + let algorithm: KDF.Insecure.PBKDF2.HashFunction + let iterations: Int + let salt: [UInt8] + let hash: [UInt8] + } + + private static func parsePassword(_ string: String) -> ParsedPassword? { + // Expected format: $pbkdf2-$$$ + let parts = string.split(separator: "$", omittingEmptySubsequences: true) + guard parts.count == 4 else { return nil } + + // Parse algorithm + let algPart = String(parts[0]) + guard + algPart.hasPrefix("pbkdf2-"), + let algorithm = hashFunction(from: String(algPart.dropFirst(7))) + else { + return nil + } + + // Parse iterations + guard let iterations = Int(parts[1]) else { + return nil + } + + // Parse salt + guard let saltData = Data(base64Encoded: String(parts[2])) else { + return nil + } + + // Parse hash + guard let hashData = Data(base64Encoded: String(parts[3])) else { + return nil + } + + return ParsedPassword( + algorithm: algorithm, + iterations: iterations, + salt: Array(saltData), + hash: Array(hashData) + ) + } + + private static func algorithmIdentifier(for hashFunction: KDF.Insecure.PBKDF2.HashFunction) -> String { + switch hashFunction { + case .sha256: "sha256" + case .sha384: "sha384" + case .sha512: "sha512" + case .insecureSHA1: "sha1" + case .insecureSHA224: "sha224" + case .insecureMD5: "md5" + default: fatalError("Unsupported hash function") + } + } + + private static func hashFunction(from identifier: String) -> KDF.Insecure.PBKDF2.HashFunction? { + switch identifier { + case "sha256": .sha256 + case "sha384": .sha384 + case "sha512": .sha512 + case "sha1": .insecureSHA1 + case "sha224": .insecureSHA224 + case "md5": .insecureMD5 + default: nil + } + } +} diff --git a/Tests/AuthenticationTests/PBKDF2Tests.swift b/Tests/AuthenticationTests/PBKDF2Tests.swift new file mode 100644 index 0000000..f585a76 --- /dev/null +++ b/Tests/AuthenticationTests/PBKDF2Tests.swift @@ -0,0 +1,124 @@ +import Authentication +import CryptoExtras +import Testing + +@Suite("PBKDF2 Tests") +struct PBKDF2Tests { + @Test("Hash and verify round trip") + func hashAndVerify() throws { + let hasher = PBKDF2Hasher() + let password = "secretPassword123" + let digest = try hasher.hash(password) + let result = try hasher.verify(password, created: digest) + #expect(result, "Password should verify against its own hash") + } + + @Test("Verification fails for wrong password") + func verifyFails() throws { + let hasher = PBKDF2Hasher() + let digest = try hasher.hash("correctPassword") + let result = try hasher.verify("wrongPassword", created: digest) + #expect(result == false) + } + + @Test("Empty digest returns false") + func emptyDigest() throws { + let hasher = PBKDF2Hasher() + let result = try hasher.verify("password", created: "") + #expect(result == false) + } + + @Test("Invalid digest format returns false") + func invalidDigestFormat() throws { + let hasher = PBKDF2Hasher() + // No separator + let result1 = try hasher.verify("password", created: "invaliddigest") + #expect(result1 == false) + + // Multiple separators + let result2 = try hasher.verify("password", created: "part1$part2$part3") + #expect(result2 == false) + } + + @Test("Invalid base64 in digest returns false") + func invalidBase64() throws { + let hasher = PBKDF2Hasher() + let result = try hasher.verify("password", created: "!!!invalid$###base64") + #expect(result == false) + } + + @Test("Different hash functions produce different outputs") + func differentHashFunctions() throws { + let sha256Hasher = PBKDF2Hasher(pseudoRandomFunction: .sha256) + let sha512Hasher = PBKDF2Hasher(pseudoRandomFunction: .sha512) + + let password = "testPassword" + let digest256 = try sha256Hasher.hash(password) + let digest512 = try sha512Hasher.hash(password) + + #expect(digest256 != digest512) + + #expect(try sha256Hasher.verify(password, created: digest256)) + #expect(try sha512Hasher.verify(password, created: digest512)) + + #expect(try sha256Hasher.verify(password, created: digest512) == false) + #expect(try sha512Hasher.verify(password, created: digest256) == false) + } + + @Test("Same password with different salts produces different hashes") + func differentSalts() throws { + let hasher = PBKDF2Hasher() + let password = "samePassword" + + let digest1 = try hasher.hash(password) + let digest2 = try hasher.hash(password) + + #expect(digest1 != digest2) + + #expect(try hasher.verify(password, created: digest1)) + #expect(try hasher.verify(password, created: digest2)) + } + + @Test("Empty password can be hashed and verified") + func emptyPassword() throws { + let hasher = PBKDF2Hasher() + let digest = try hasher.hash("") + let result = try hasher.verify("", created: digest) + #expect(result) + } + + @Test("Unicode passwords work correctly") + func unicodePassword() throws { + let hasher = PBKDF2Hasher() + let password = "пароль密码🔐" + let digest = try hasher.hash(password) + let result = try hasher.verify(password, created: digest) + #expect(result) + } + + @Test("Long password works correctly") + func longPassword() throws { + let hasher = PBKDF2Hasher() + let password = String(repeating: "a", count: 10000) + let digest = try hasher.hash(password) + let result = try hasher.verify(password, created: digest) + #expect(result) + } + + @Test( + "All supported hash functions work", + arguments: [ + KDF.Insecure.PBKDF2.HashFunction.sha256, + KDF.Insecure.PBKDF2.HashFunction.sha384, + KDF.Insecure.PBKDF2.HashFunction.sha512, + KDF.Insecure.PBKDF2.HashFunction.insecureSHA1, + KDF.Insecure.PBKDF2.HashFunction.insecureSHA224, + ]) + func allHashFunctions(hashFunction: KDF.Insecure.PBKDF2.HashFunction) throws { + let hasher = PBKDF2Hasher(pseudoRandomFunction: hashFunction, iterations: 1000) + let password = "testAllFunctions" + let digest = try hasher.hash(password) + let result = try hasher.verify(password, created: digest) + #expect(result, "Hash function should work for hashing and verification") + } +} From 2f8d58aa99178fe96cbff3f89ad72534d4e1ef49 Mon Sep 17 00:00:00 2001 From: Paul Toffoloni Date: Wed, 17 Dec 2025 16:02:11 +0100 Subject: [PATCH 2/5] Nit --- Sources/Authentication/Passwords/PBKDF2Hasher.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/Authentication/Passwords/PBKDF2Hasher.swift b/Sources/Authentication/Passwords/PBKDF2Hasher.swift index 90f3f44..de56fac 100644 --- a/Sources/Authentication/Passwords/PBKDF2Hasher.swift +++ b/Sources/Authentication/Passwords/PBKDF2Hasher.swift @@ -73,13 +73,13 @@ public struct PBKDF2Hasher: PasswordHasher { let keyData = unsafe key.withUnsafeBytes { unsafe Data($0) } - // PHC format: $pbkdf2-$$$ + // $pbkdf2-$$$ let algorithmId = Self.algorithmIdentifier(for: pseudoRandomFunction) let b64Salt = Data(salt).base64EncodedString() let b64Hash = keyData.base64EncodedString() - let phcString = "$pbkdf2-\(algorithmId)$\(iterations)$\(b64Salt)$\(b64Hash)" - return Array(phcString.utf8) + let passwordString = "$pbkdf2-\(algorithmId)$\(iterations)$\(b64Salt)$\(b64Hash)" + return Array(passwordString.utf8) } /// Verifies a password against a hash. From e1db0d6f9724718ea6659e5c4b2b7a4a52182a8a Mon Sep 17 00:00:00 2001 From: Paul Toffoloni Date: Mon, 5 Jan 2026 17:39:38 +0100 Subject: [PATCH 3/5] Address review --- Package.swift | 9 ++- .../Passwords/PBKDF2Hasher.swift | 59 +++++++++---------- Tests/AuthenticationTests/PBKDF2Tests.swift | 14 +++-- 3 files changed, 44 insertions(+), 38 deletions(-) diff --git a/Package.swift b/Package.swift index 727564a..c2b6316 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:6.2 +// swift-tools-version:6.2.3 import PackageDescription let extraSettings: [SwiftSetting] = [ @@ -29,6 +29,13 @@ let package = Package( products: [ .library(name: "Authentication", targets: ["Authentication"]) ], + traits: [ + .init( + name: "PBKDF2", + description: "A password hasher using PBKDF2" + ), + .default(enabledTraits: []), + ], dependencies: [ .package(url: "https://github.com/apple/swift-crypto.git", from: "4.0.0") ], diff --git a/Sources/Authentication/Passwords/PBKDF2Hasher.swift b/Sources/Authentication/Passwords/PBKDF2Hasher.swift index de56fac..95cc780 100644 --- a/Sources/Authentication/Passwords/PBKDF2Hasher.swift +++ b/Sources/Authentication/Passwords/PBKDF2Hasher.swift @@ -1,4 +1,5 @@ -public import CryptoExtras +#if PBKDF2 +import CryptoExtras #if canImport(FoundationEssentials) public import FoundationEssentials @@ -14,7 +15,7 @@ public import Foundation /// This format is compatible with passlib and other common PBKDF2 implementations. /// See: https://passlib.readthedocs.io/en/stable/lib/passlib.hash.pbkdf2_digest.html public struct PBKDF2Hasher: PasswordHasher { - let pseudoRandomFunction: KDF.Insecure.PBKDF2.HashFunction + let pseudoRandomFunction: HashFunction let outputByteCount: Int let iterations: Int @@ -27,7 +28,7 @@ public struct PBKDF2Hasher: PasswordHasher { /// - Note: the parameters passed in here will only be used for hashing, verification /// will rely solely on the parameters inside of the hash. public init( - pseudoRandomFunction: KDF.Insecure.PBKDF2.HashFunction = .sha256, + pseudoRandomFunction: HashFunction = .sha256, iterations: Int? = nil ) { self.pseudoRandomFunction = pseudoRandomFunction @@ -41,7 +42,6 @@ public struct PBKDF2Hasher: PasswordHasher { case .insecureSHA1: 1_300_000 case .insecureSHA224: 800_000 case .insecureMD5: 1_600_000 - default: fatalError("Unsupported hash function") } self.iterations = iterations ?? defaultIterations @@ -53,7 +53,6 @@ public struct PBKDF2Hasher: PasswordHasher { case .insecureSHA224: 28 case .insecureSHA1: 20 case .insecureMD5: 16 - default: fatalError("Unsupported hash function") } } @@ -66,7 +65,7 @@ public struct PBKDF2Hasher: PasswordHasher { let key = try KDF.Insecure.PBKDF2.deriveKey( from: password, salt: salt, - using: pseudoRandomFunction, + using: pseudoRandomFunction.cryptoHashFunction, outputByteCount: outputByteCount, unsafeUncheckedRounds: iterations ) @@ -74,7 +73,7 @@ public struct PBKDF2Hasher: PasswordHasher { let keyData = unsafe key.withUnsafeBytes { unsafe Data($0) } // $pbkdf2-$$$ - let algorithmId = Self.algorithmIdentifier(for: pseudoRandomFunction) + let algorithmId = pseudoRandomFunction.rawValue let b64Salt = Data(salt).base64EncodedString() let b64Hash = keyData.base64EncodedString() @@ -100,7 +99,7 @@ public struct PBKDF2Hasher: PasswordHasher { let key = try KDF.Insecure.PBKDF2.deriveKey( from: password, salt: parsed.salt, - using: parsed.algorithm, + using: parsed.algorithm.cryptoHashFunction, outputByteCount: parsed.hash.count, unsafeUncheckedRounds: parsed.iterations ) @@ -111,7 +110,7 @@ public struct PBKDF2Hasher: PasswordHasher { } private struct ParsedPassword { - let algorithm: KDF.Insecure.PBKDF2.HashFunction + let algorithm: HashFunction let iterations: Int let salt: [UInt8] let hash: [UInt8] @@ -126,7 +125,7 @@ public struct PBKDF2Hasher: PasswordHasher { let algPart = String(parts[0]) guard algPart.hasPrefix("pbkdf2-"), - let algorithm = hashFunction(from: String(algPart.dropFirst(7))) + let algorithm = HashFunction(rawValue: String(algPart.dropFirst(7))) else { return nil } @@ -154,27 +153,25 @@ public struct PBKDF2Hasher: PasswordHasher { ) } - private static func algorithmIdentifier(for hashFunction: KDF.Insecure.PBKDF2.HashFunction) -> String { - switch hashFunction { - case .sha256: "sha256" - case .sha384: "sha384" - case .sha512: "sha512" - case .insecureSHA1: "sha1" - case .insecureSHA224: "sha224" - case .insecureMD5: "md5" - default: fatalError("Unsupported hash function") - } - } - - private static func hashFunction(from identifier: String) -> KDF.Insecure.PBKDF2.HashFunction? { - switch identifier { - case "sha256": .sha256 - case "sha384": .sha384 - case "sha512": .sha512 - case "sha1": .insecureSHA1 - case "sha224": .insecureSHA224 - case "md5": .insecureMD5 - default: nil + @nonexhaustive + public enum HashFunction: String, Sendable { + case insecureMD5 = "insecure_md5" + case insecureSHA1 = "insecure_sha1" + case insecureSHA224 = "insecure_sha224" + case sha256 = "sha256" + case sha384 = "sha384" + case sha512 = "sha512" + + var cryptoHashFunction: KDF.Insecure.PBKDF2.HashFunction { + switch self { + case .insecureMD5: .insecureMD5 + case .insecureSHA1: .insecureSHA1 + case .insecureSHA224: .insecureSHA224 + case .sha256: .sha256 + case .sha384: .sha384 + case .sha512: .sha512 + } } } } +#endif diff --git a/Tests/AuthenticationTests/PBKDF2Tests.swift b/Tests/AuthenticationTests/PBKDF2Tests.swift index f585a76..c7286e6 100644 --- a/Tests/AuthenticationTests/PBKDF2Tests.swift +++ b/Tests/AuthenticationTests/PBKDF2Tests.swift @@ -1,3 +1,4 @@ +#if PBKDF2 import Authentication import CryptoExtras import Testing @@ -108,13 +109,13 @@ struct PBKDF2Tests { @Test( "All supported hash functions work", arguments: [ - KDF.Insecure.PBKDF2.HashFunction.sha256, - KDF.Insecure.PBKDF2.HashFunction.sha384, - KDF.Insecure.PBKDF2.HashFunction.sha512, - KDF.Insecure.PBKDF2.HashFunction.insecureSHA1, - KDF.Insecure.PBKDF2.HashFunction.insecureSHA224, + PBKDF2Hasher.HashFunction.sha256, + PBKDF2Hasher.HashFunction.sha384, + PBKDF2Hasher.HashFunction.sha512, + PBKDF2Hasher.HashFunction.insecureSHA1, + PBKDF2Hasher.HashFunction.insecureSHA224, ]) - func allHashFunctions(hashFunction: KDF.Insecure.PBKDF2.HashFunction) throws { + func allHashFunctions(hashFunction: PBKDF2Hasher.HashFunction) throws { let hasher = PBKDF2Hasher(pseudoRandomFunction: hashFunction, iterations: 1000) let password = "testAllFunctions" let digest = try hasher.hash(password) @@ -122,3 +123,4 @@ struct PBKDF2Tests { #expect(result, "Hash function should work for hashing and verification") } } +#endif From d86dd1272c3bede987d9670ca137550514cc8457 Mon Sep 17 00:00:00 2001 From: Paul Toffoloni Date: Tue, 6 Jan 2026 10:27:00 +0100 Subject: [PATCH 4/5] Add docs --- README.md | 26 +++++++-- .../Docs.docc/PasswordHashing.md | 56 ++++++++++++++++++- 2 files changed, 77 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 1556c4b..e3ff559 100644 --- a/README.md +++ b/README.md @@ -37,13 +37,15 @@ targets: [ ## Password Hashing -Securely hash and verify user passwords using the bcrypt algorithm or the `PasswordHasher` algorithm: +Securely hash and verify user passwords using the bcrypt algorithm, the `PasswordHasher` protocol or the PBKDF2 algorithm: ```swift import Authentication // Create a hasher with default cost (12) let hasher = BcryptHasher() +// Or use PBKDF2 +let hasher = PBKDF2Hasher() // Or a hasher injected in let hasher: PasswordHasher @@ -55,12 +57,14 @@ let isValid = try hasher.verify("secretPassword123", created: hash) // isValid == true ``` -### Configuring Cost +### Configuration + +#### Bcrypt The cost parameter controls how computationally expensive the hashing operation is. Higher costs provide more security but take longer to compute: ```swift -// Create a hasher with custom cost (valid range: 4-31) +// Create a bcrypt hasher with custom cost (valid range: 4-31) let hasher = BcryptHasher(cost: 14) let hash = try hasher.hash("myPassword") @@ -68,6 +72,20 @@ let hash = try hasher.hash("myPassword") > **Note**: Increasing the cost by 1 doubles the computation time. A cost of 12 takes approximately 250ms on modern hardware. +#### PBKDF2 + +In PBKDF2 you can configure the number of iterations and hashing function. There are sensible standards in place already depending on the hash algorithm used, so only adjust the iterations if necessary: + +```swift +// Create a PBKDF2 hasher with custom iterations +let hasher = PBKDF2Hasher( + pseudoRandomFunction: .sha256, + iterations: 600_000, +) +let hash = try hasher.hash("myPassword") +``` + + ## One-Time Passwords (OTP) Generate RFC-compliant HOTP and TOTP codes for multi-factor authentication. @@ -137,4 +155,4 @@ let codes = totp.generate(time: Date(), range: 1) // Check if user's code matches any valid code let isValid = codes.contains(userCode) -``` \ No newline at end of file +``` diff --git a/Sources/Authentication/Docs.docc/PasswordHashing.md b/Sources/Authentication/Docs.docc/PasswordHashing.md index 8b428f7..676863e 100644 --- a/Sources/Authentication/Docs.docc/PasswordHashing.md +++ b/Sources/Authentication/Docs.docc/PasswordHashing.md @@ -10,6 +10,8 @@ The Authentication library provides a robust password hashing system built on th - **Built-in salting**: Each hash includes a unique random salt - **Timing-safe comparison**: Prevents timing attacks during verification +If you prefer, you can also use the PBKDF2 algorithm for password hashing by utilizing the `PBKDF2Hasher`. PBKDF2 is a general key derivation function that is widely used for securely hashing passwords. It is considered less secure than bcrypt against modern hardware attacks. + ### Basic Usage #### ``PasswordHasher`` @@ -41,7 +43,27 @@ let isValid = try hasher.verify("secretPassword123", created: hash) // isValid == true ``` -### Configuring Cost +#### ``PBKDF2Hasher`` + +Use ``PBKDF2Hasher`` to hash and verify passwords using the PBKDF2 algorithm: + +```swift +import Authentication + +// Create a PBKDF2 hasher with default settings (SHA256, 600,000 iterations) +let hasher = PBKDF2Hasher() + +// Hash a password +let hash = try hasher.hash("secretPassword123") + +// Verify a password against a hash +let isValid = try hasher.verify("secretPassword123", created: hash) +// isValid == true +``` + +### Configuration + +#### Bcrypt The cost parameter controls how computationally expensive the hashing operation is. Higher costs provide more security but take longer to compute. The default cost of 12 is suitable for most applications. @@ -54,6 +76,19 @@ let hash = try hasher.hash("myPassword") > Important: Increasing the cost by 1 doubles the computation time. A cost of 12 takes approximately 250ms on modern hardware. Choose a cost that provides adequate security while maintaining acceptable response times for your users. +#### PBKDF2 + +In PBKDF2, you can configure the number of iterations and hashing function. There are sensible standards in place already depending on the hash algorithm used, so only adjust the iterations if necessary: + +```swift +// Create a PBKDF2 hasher with custom iterations +let hasher = PBKDF2Hasher( + pseudoRandomFunction: .sha256, + iterations: 600_000, +) +let hash = try hasher.hash("myPassword") +``` + ### Low-Level API For more control, you can use the ``VaporBcrypt`` type directly: @@ -68,6 +103,25 @@ let hash = try VaporBcrypt.hash("password", cost: 12) let isValid = try VaporBcrypt.verify("password", created: hash) ``` +Or, for PBKDF2,: + +```swift +import Authentication + +// Hash with explicit parameters +let hash = try PBKDF2Hasher.hash( + Array("password".utf8), + pseudoRandomFunction: .sha256, + iterations: 600_000 +) + +// Verify password +let isValid = try PBKDF2Hasher.verify( + Array("password".utf8), + created: hash +) +``` + ### Testing with PlaintextHasher For testing purposes, you can use ``PlaintextHasher`` which stores passwords without hashing: From f7d25b0d69e2bebeb983d86e6ec07e214e7fd63e Mon Sep 17 00:00:00 2001 From: Paul Toffoloni Date: Tue, 6 Jan 2026 10:53:28 +0100 Subject: [PATCH 5/5] Format --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 9bbe494..08b5ec2 100644 --- a/Package.swift +++ b/Package.swift @@ -33,7 +33,7 @@ let package = Package( traits: [ .trait(name: "bcrypt"), .trait(name: "OTP"), - .trait(name: "PBKDF2",), + .trait(name: "PBKDF2"), .default(enabledTraits: [ "bcrypt", "OTP",