|
| 1 | +#if PBKDF2 |
| 2 | +import CryptoExtras |
| 3 | + |
| 4 | +#if canImport(FoundationEssentials) |
| 5 | +public import FoundationEssentials |
| 6 | +#else |
| 7 | +public import Foundation |
| 8 | +#endif |
| 9 | + |
| 10 | +/// A password hasher using PBKDF2 with configurable hash function and iterations. |
| 11 | +/// |
| 12 | +/// The output format is a modular crypt format string: |
| 13 | +/// `$pbkdf2-<algorithm>$<iterations>$<base64-salt>$<base64-hash>` |
| 14 | +/// |
| 15 | +/// This format is compatible with passlib and other common PBKDF2 implementations. |
| 16 | +/// See: https://passlib.readthedocs.io/en/stable/lib/passlib.hash.pbkdf2_digest.html |
| 17 | +public struct PBKDF2Hasher: PasswordHasher { |
| 18 | + let pseudoRandomFunction: HashFunction |
| 19 | + let outputByteCount: Int |
| 20 | + let iterations: Int |
| 21 | + |
| 22 | + /// Creates a PBKDF2 password hasher. |
| 23 | + /// |
| 24 | + /// - Parameters: |
| 25 | + /// - pseudoRandomFunction: The hash function to use. Defaults to SHA-256. |
| 26 | + /// - iterations: The number of PBKDF2 iterations. If nil, uses OWASP-recommended |
| 27 | + /// defaults based on the hash function. |
| 28 | + /// - Note: the parameters passed in here will only be used for hashing, verification |
| 29 | + /// will rely solely on the parameters inside of the hash. |
| 30 | + public init( |
| 31 | + pseudoRandomFunction: HashFunction = .sha256, |
| 32 | + iterations: Int? = nil |
| 33 | + ) { |
| 34 | + self.pseudoRandomFunction = pseudoRandomFunction |
| 35 | + |
| 36 | + // OWASP recommendations: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2 |
| 37 | + let defaultIterations: Int = |
| 38 | + switch pseudoRandomFunction { |
| 39 | + case .sha256: 600_000 |
| 40 | + case .sha384: 400_000 |
| 41 | + case .sha512: 210_000 |
| 42 | + case .insecureSHA1: 1_300_000 |
| 43 | + case .insecureSHA224: 800_000 |
| 44 | + case .insecureMD5: 1_600_000 |
| 45 | + } |
| 46 | + self.iterations = iterations ?? defaultIterations |
| 47 | + |
| 48 | + self.outputByteCount = |
| 49 | + switch pseudoRandomFunction { |
| 50 | + case .sha256: 32 |
| 51 | + case .sha384: 48 |
| 52 | + case .sha512: 64 |
| 53 | + case .insecureSHA224: 28 |
| 54 | + case .insecureSHA1: 20 |
| 55 | + case .insecureMD5: 16 |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + /// Hashes a password using PBKDF2. |
| 60 | + /// |
| 61 | + /// - Parameter password: The password to hash. |
| 62 | + /// - Returns: The hash string as UTF-8 bytes. |
| 63 | + public func hash<Password>(_ password: Password) throws -> [UInt8] where Password: DataProtocol { |
| 64 | + let salt = [UInt8].random(count: 16) |
| 65 | + let key = try KDF.Insecure.PBKDF2.deriveKey( |
| 66 | + from: password, |
| 67 | + salt: salt, |
| 68 | + using: pseudoRandomFunction.cryptoHashFunction, |
| 69 | + outputByteCount: outputByteCount, |
| 70 | + unsafeUncheckedRounds: iterations |
| 71 | + ) |
| 72 | + |
| 73 | + let keyData = unsafe key.withUnsafeBytes { unsafe Data($0) } |
| 74 | + |
| 75 | + // $pbkdf2-<alg>$<iterations>$<b64salt>$<b64hash> |
| 76 | + let algorithmId = pseudoRandomFunction.rawValue |
| 77 | + let b64Salt = Data(salt).base64EncodedString() |
| 78 | + let b64Hash = keyData.base64EncodedString() |
| 79 | + |
| 80 | + let passwordString = "$pbkdf2-\(algorithmId)$\(iterations)$\(b64Salt)$\(b64Hash)" |
| 81 | + return Array(passwordString.utf8) |
| 82 | + } |
| 83 | + |
| 84 | + /// Verifies a password against a hash. |
| 85 | + /// |
| 86 | + /// - Parameters: |
| 87 | + /// - password: The password to verify. |
| 88 | + /// - digest: The stored hash. |
| 89 | + /// - Returns: `true` if the password matches, `false` otherwise. |
| 90 | + public func verify<Password, Digest>(_ password: Password, created digest: Digest) throws -> Bool |
| 91 | + where Password: DataProtocol, Digest: DataProtocol { |
| 92 | + guard !digest.isEmpty else { return false } |
| 93 | + |
| 94 | + let digestString = String(decoding: digest, as: UTF8.self) |
| 95 | + guard let parsed = Self.parsePassword(digestString), parsed.algorithm == pseudoRandomFunction else { |
| 96 | + return false |
| 97 | + } |
| 98 | + |
| 99 | + let key = try KDF.Insecure.PBKDF2.deriveKey( |
| 100 | + from: password, |
| 101 | + salt: parsed.salt, |
| 102 | + using: parsed.algorithm.cryptoHashFunction, |
| 103 | + outputByteCount: parsed.hash.count, |
| 104 | + unsafeUncheckedRounds: parsed.iterations |
| 105 | + ) |
| 106 | + |
| 107 | + let keyData = unsafe key.withUnsafeBytes { unsafe Data($0) } |
| 108 | + |
| 109 | + return keyData.elementsEqual(parsed.hash) |
| 110 | + } |
| 111 | + |
| 112 | + private struct ParsedPassword { |
| 113 | + let algorithm: HashFunction |
| 114 | + let iterations: Int |
| 115 | + let salt: [UInt8] |
| 116 | + let hash: [UInt8] |
| 117 | + } |
| 118 | + |
| 119 | + private static func parsePassword(_ string: String) -> ParsedPassword? { |
| 120 | + // Expected format: $pbkdf2-<alg>$<iterations>$<b64salt>$<b64hash> |
| 121 | + let parts = string.split(separator: "$", omittingEmptySubsequences: true) |
| 122 | + guard parts.count == 4 else { return nil } |
| 123 | + |
| 124 | + // Parse algorithm |
| 125 | + let algPart = String(parts[0]) |
| 126 | + guard |
| 127 | + algPart.hasPrefix("pbkdf2-"), |
| 128 | + let algorithm = HashFunction(rawValue: String(algPart.dropFirst(7))) |
| 129 | + else { |
| 130 | + return nil |
| 131 | + } |
| 132 | + |
| 133 | + // Parse iterations |
| 134 | + guard let iterations = Int(parts[1]) else { |
| 135 | + return nil |
| 136 | + } |
| 137 | + |
| 138 | + // Parse salt |
| 139 | + guard let saltData = Data(base64Encoded: String(parts[2])) else { |
| 140 | + return nil |
| 141 | + } |
| 142 | + |
| 143 | + // Parse hash |
| 144 | + guard let hashData = Data(base64Encoded: String(parts[3])) else { |
| 145 | + return nil |
| 146 | + } |
| 147 | + |
| 148 | + return ParsedPassword( |
| 149 | + algorithm: algorithm, |
| 150 | + iterations: iterations, |
| 151 | + salt: Array(saltData), |
| 152 | + hash: Array(hashData) |
| 153 | + ) |
| 154 | + } |
| 155 | + |
| 156 | + @nonexhaustive |
| 157 | + public enum HashFunction: String, Sendable { |
| 158 | + case insecureMD5 = "insecure_md5" |
| 159 | + case insecureSHA1 = "insecure_sha1" |
| 160 | + case insecureSHA224 = "insecure_sha224" |
| 161 | + case sha256 = "sha256" |
| 162 | + case sha384 = "sha384" |
| 163 | + case sha512 = "sha512" |
| 164 | + |
| 165 | + var cryptoHashFunction: KDF.Insecure.PBKDF2.HashFunction { |
| 166 | + switch self { |
| 167 | + case .insecureMD5: .insecureMD5 |
| 168 | + case .insecureSHA1: .insecureSHA1 |
| 169 | + case .insecureSHA224: .insecureSHA224 |
| 170 | + case .sha256: .sha256 |
| 171 | + case .sha384: .sha384 |
| 172 | + case .sha512: .sha512 |
| 173 | + } |
| 174 | + } |
| 175 | + } |
| 176 | +} |
| 177 | +#endif |
0 commit comments