Skip to content

Commit 1ed4202

Browse files
committed
Add verification
1 parent a573e64 commit 1ed4202

File tree

3 files changed

+29
-10
lines changed

3 files changed

+29
-10
lines changed

Sources/Bcrypt/BcryptVersion.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ public enum BcryptVersion {
2727
var identifier: [UInt8] {
2828
[.separator, majorVersion, minorVersion, .separator] // $2x$
2929
}
30+
31+
init(identifier: [UInt8]) {
32+
switch identifier {
33+
case [0x32, 0x61]: self = .v2a
34+
case [0x32, 0x62]: self = .v2b
35+
default: fatalError("Invalid identifier")
36+
}
37+
}
3038
}
3139

3240
extension UInt8 {

Sources/Bcrypt/Verifier.swift

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
struct Verifier {
2-
private let version: BcryptVersion
3-
private let hasher: Hasher
4-
5-
init(version: BcryptVersion) {
6-
self.version = version
7-
self.hasher = Hasher(version: version)
8-
}
9-
102
@inlinable
113
public func verify(password: [UInt8], hash goodHash: [UInt8]) throws -> Bool {
12-
let hash = try hasher.hash(password: password, cost: 6, salt: goodHash)
13-
return hash == goodHash
4+
let prefix = goodHash.prefix(7)
5+
6+
let version = BcryptVersion(identifier: Array(prefix[1...2]))
7+
let cost = prefix[4...5].reduce(0) { $0 * 10 + Int($1 - 48) }
8+
9+
let salt = Array(goodHash[7...28])
10+
11+
let hasher = Hasher(version: version)
12+
let newHash = try hasher.hash(password: password, cost: cost, salt: salt)
13+
14+
return newHash == goodHash
1415
}
1516

1617
}

Tests/BcryptTests/BcryptTests.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,16 @@ struct BcryptTests {
6464
"Expected: \(testVector.expectedHash), got: \(String(decoding: hash, as: UTF8.self))")
6565
}
6666
}
67+
68+
@Test("End to end")
69+
func endToEnd() throws {
70+
let password = "password"
71+
let cost = 12
72+
73+
let hash = try Hasher().hash(password: Array(password.utf8), cost: cost)
74+
let verifier = Verifier()
75+
#expect(try verifier.verify(password: Array(password.utf8), hash: hash))
76+
}
6777

6878
@Test("Correct Version")
6979
func correctVersion() throws {

0 commit comments

Comments
 (0)