Skip to content

Instantly share code, notes, and snippets.

@m3tti
Last active August 31, 2024 04:06
Show Gist options
  • Select an option

  • Save m3tti/6d74f0e8ead6f63c6a955e29ec6d1067 to your computer and use it in GitHub Desktop.

Select an option

Save m3tti/6d74f0e8ead6f63c6a955e29ec6d1067 to your computer and use it in GitHub Desktop.
Babashka / Clojure password hashing
(import java.security.SecureRandom)
(import javax.crypto.SecretKeyFactory)
(import javax.crypto.spec.PBEKeySpec)
(defn bytes->hex [byt]
(apply str (map #(format "%02x" %) byt)))
(defn hex->bytes [hex]
(.toByteArray (BigInteger. hex 16)))
(defn hash-password
([password]
(let [salt (byte-array 4)]
(.nextBytes (SecureRandom.) salt)
(hash-password password salt)))
([password salt]
(let [spec (PBEKeySpec. (char-array password) salt 65536 128)
factory (SecretKeyFactory/getInstance "PBKDF2WithHmacSHA256")
byte-data (.getEncoded (.generateSecret factory spec))]
(str/join "$"
[(bytes->hex byte-data)
(bytes->hex salt)]))))
(defn get-salt [password-hash]
(second (str/split password-hash #"\$")))
(defn password= [password-hash given-password]
(let [salt (get-salt password-hash)]
(= password-hash (hash-password given-password (hex->bytes salt)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment