-
Notifications
You must be signed in to change notification settings - Fork 1
/
hash.cljc
86 lines (79 loc) · 2.19 KB
/
hash.cljc
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
(ns uniformity.hash
(:require #?(:clj [uniformity.internals.java.hash :as internals]
:cljs [uniformity.internals.js.hash :as internals])
[uniformity.util :as util]))
(defn ^:private hash-format [hash format]
(case format
:bytes hash
:hex (util/hex-encode hash)
:base64 (util/base64-encode hash)
:base64-urlsafe (util/base64-encode-urlsafe hash)
(throw (ex-info "Unidentified hash format"
{:format format}))))
(defn md5
"Produces a MD5 hash of input bytes.
Optional :format parameter determines output:
:bytes
:hex (default)
:base64
:base64-urlsafe"
[bytes
& {:keys [format] :or {format :hex}}]
(hash-format (internals/md5 bytes)
format))
(defn sha1
"Produces a SHA-1 hash of input bytes.
Optional :format parameter determines output:
:bytes
:hex (default)
:base64
:base64-urlsafe"
[bytes
& {:keys [format] :or {format :hex}}]
(hash-format (internals/sha1 bytes)
format))
(defn sha256
"Produces a SHA-256 hash of input bytes.
Optional :format parameter determines output:
:bytes
:hex (default)
:base64
:base64-urlsafe"
[bytes
& {:keys [format] :or {format :hex}}]
(hash-format (internals/sha256 bytes)
format))
(defn sha384
"Produces a SHA-384 hash of input bytes.
Optional :format parameter determines output:
:bytes
:hex (default)
:base64
:base64-urlsafe"
[bytes
& {:keys [format] :or {format :hex}}]
(hash-format (internals/sha384 bytes)
format))
(defn sha512
"Produces a SHA-512 hash of input bytes.
Optional :format parameter determines output:
:bytes
:hex (default)
:base64
:base64-urlsafe"
[bytes
& {:keys [format] :or {format :hex}}]
(hash-format (internals/sha512 bytes)
format))
(defn hashes-equal?
"Compares equality of two hashes by comparing every element
to inhibit timing attacks."
[hash1 hash2]
(if (not= (count hash1) (count hash2))
false
(reduce (fn [equals idx]
(and (= (get hash1 idx)
(get hash2 idx))
equals))
true
(range (count hash1)))))