Gangmax Blog

自由之思想,独立之精神

Salted Hash Implementation in Clojure

| Comments

This is a salted hash implementation mentioned here in Clojure.

project.clj
1
2
3
4
5
6
7
8
9
(defproject salt "0.1.0-SNAPSHOT"
  :description "A hash with salt implementation"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.8.0"]
               [crypto-random "1.2.0"]
               [digest "1.4.5"]]
  :main salt.core)
core.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
(ns salt.core
  (:require
    [crypto.random :refer [base64]]
    [digest :refer :all]
    [clojure.string :refer [lower-case]]))

(defn get-all-hash-algorithms
  "Get a set of all supported hash algorithms."
  []
  (algorithms))

(defn gen-salt
  "Generate a salt string with given length."
  [size]
  (base64 (* (/ size 4) 3)))

(defn simple-concat
  "Return a function which concatenates the password after the salt."
  [password salt]
  (str salt password))

(defn gen-hash
  "Generate a hash string for a given password and salted string."
  ([password saltstr] (gen-hash password saltstr simple-concat "digest/sha-256"))
  ([password saltstr concatfunc] (gen-hash password saltstr concatfunc "digest/sha-256"))
  ([password saltstr concatfunc hashalgo]
    (let
      [func (-> hashalgo symbol resolve)]
      (func (concatfunc password saltstr)))))

(defn -main [& args]
  (println "The available hash methods:")
  (doseq [x (get-all-hash-algorithms)] (prn (lower-case x)))
  (doseq [x (take 10 (range))]
    (prn (gen-hash "123456"))
    (prn (gen-hash "123456" (gen-salt 64) simple-concat "digest/sha-256"))))

Comments