-
Notifications
You must be signed in to change notification settings - Fork 11
/
hash.clj
63 lines (53 loc) · 1.82 KB
/
hash.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
(ns framework.auth.hash
"Cryptography helper for creating, and resolving passwords.
Supported algorithms are bcrypr, pbkdf2, and scrypt.
The required algorithm should be in (-> state :deps :auth :hash-algorithm)"
(:require
[crypto.password.bcrypt :as hash-b]
[crypto.password.pbkdf2 :as hash-p]
[crypto.password.scrypt :as hash-s]))
(def supported [:bcrypt :pbkdf2 :scrypt])
(defn- dispatch
([state password]
(dispatch state password nil))
([{{{hash-algorithm :hash-algorithm} :auth} :deps} _ _]
{:pre [(some #(= hash-algorithm %) supported)]}
hash-algorithm))
(defmulti make
"Creating an encrypted version for store password."
dispatch)
(defmethod make :bcrypt
[{{:keys [bcrypt-settings]
:or {bcrypt-settings {:work-factor 11}}} :deps/auth}
password]
(hash-b/encrypt password (:work-factor bcrypt-settings)))
(defmethod make :scrypt
[{{:keys [scrypt-settings]
:or {scrypt-settings {:cpu-cost 32768
:memory-cost 8
:parallelization 1}}} :deps/auth}
password]
(hash-s/encrypt
password
(:cpu-cost scrypt-settings)
(:memory-cost scrypt-settings)
(:parallelization scrypt-settings)))
(defmethod make :pbkdf2
[{{:keys [pbkdf2-settings]
:or {pbkdf2-settings {:type :sha1
:iterations 100000}}} :deps/auth}
password]
(hash-p/encrypt
password
(:iterations pbkdf2-settings)
(if (= :sha1 (:type pbkdf2-settings))
"HMAC-SHA1" "HMAC-SHA256")))
(defmulti check
"Validating password."
dispatch)
(defmethod check :bcrypt [_ password encrypted]
(hash-b/check password encrypted))
(defmethod check :scrypt [_ password encrypted]
(hash-s/check password encrypted))
(defmethod check :pbkdf2 [_ password encrypted]
(hash-p/check password encrypted))