0 | module Crypto.BCrypt
 1 |
 2 | import Crypto.BCrypt.FFI
 3 | import Crypto.BCrypt.Types
 4 |
 5 | %default total
 6 |
 7 | --------------------------------------------------------------------------------
 8 | --          Salt generation
 9 | --------------------------------------------------------------------------------
10 |
11 | ||| Generate a new bcrypt salt.
12 | |||
13 | ||| The supplied cost factor should typically be between 4 and 31 inclusive.
14 | |||
15 | ||| Common production values today are 10–14 depending on the desired computational cost.
16 | |||
17 | export
18 | genSalt : WorkFactor -> IO String
19 | genSalt (MkWorkFactor wf) =
20 |   primIO $ prim__bcryptGenSalt wf
21 |
22 | --------------------------------------------------------------------------------
23 | --          Password hashing
24 | --------------------------------------------------------------------------------
25 |
26 | ||| Hash a password using a newly generated bcrypt salt.
27 | |||
28 | ||| The supplied cost factor determines the bcrypt work factor.
29 | |||
30 | export
31 | hashPassword : String -> WorkFactor -> IO String
32 | hashPassword password (MkWorkFactor wf) =
33 |   primIO $ prim__bcryptHash password wf
34 |
35 | ||| Hash a password using an existing bcrypt salt or bcrypt hash.
36 | |||
37 | ||| This is useful when reproducing an existing hash or when deterministic hashing is desired for testing.
38 | |||
39 | export
40 | hashPasswordWithSalt : String -> String -> IO String
41 | hashPasswordWithSalt password salt =
42 |   primIO $ prim__bcryptHashWithSalt password salt
43 |
44 | --------------------------------------------------------------------------------
45 | --          Password validation
46 | --------------------------------------------------------------------------------
47 |
48 | ||| Validate a password against a bcrypt hash.
49 | |||
50 | ||| Returns `True` when the supplied password matches the bcrypt hash and `False` otherwise.
51 | |||
52 | export
53 | validatePassword : String -> String -> IO Bool
54 | validatePassword password hash = do
55 |   result <- primIO $ prim__bcryptValidate password hash
56 |   pure (result /= 0)
57 |