Last active
February 26, 2025 19:45
-
-
Save kubek2k/8446062 to your computer and use it in GitHub Desktop.
SHA-256 in clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn sha256 [string] | |
(let [digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes string "UTF-8"))] | |
(apply str (map (partial format "%02x") digest)))) |
Works like a charm.
This is wrong. It gets the padding wrong when converting the bytes into a hex string, and so will be correct for bytes with values 16-255 and wrong if any of the generated values are 15 or below. Do this instead:
(defn sha256 [string]
(let [digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes string "UTF-8"))]
(apply str (map (partial format "%02x") digest))))
@l0st3d OK, now it's clear. Thanks for sharing this!
@l0st3d thanks - I will update the gist according to your solution
This will use reflection for the .getBytes call. In clojure 1.12 you can change that to String/.getBytes
to avoid this.
(Can also type hint of course, but I personally like this syntax better.)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is wrong.