aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/program/aedifex/hash.lux
blob: 63511a74dfc6ef3a4a09c4139318b091ebff5a3a (plain)
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
(.module:
  [lux #*
   ["." host (#+ import:)]
   [data
    ["." binary (#+ Binary)]
    ["." text
     ["%" format (#+ format)]]
    [number
     ["." nat]]]])

## TODO: Replace with pure-Lux implementations of these algorithms
## https://en.wikipedia.org/wiki/SHA-1#SHA-1_pseudocode
## https://en.wikipedia.org/wiki/MD5#Algorithm
(import: #long java/lang/String)

(import: #long java/security/MessageDigest
  (#static getInstance [java/lang/String] java/security/MessageDigest)
  (digest [[byte]] [byte]))

(type: #export Hash
  Binary)

(template [<name> <algorithm>]
  [(def: #export (<name> value)
     (-> Binary Hash)
     (|> (java/security/MessageDigest::getInstance [<algorithm>])
         (java/security/MessageDigest::digest [value])))]

  [sha1 "SHA-1"]
  [md5 "MD5"]
  )

(def: #export representation
  (-> Hash Text)
  (binary.fold (function (_ byte representation)
                 (let [hex (:: nat.hex encode byte)
                       hex (case (text.size hex)
                             1 (format "0" hex)
                             _ hex)]
                   (format representation hex)))
               ""))