Skip to content

Instantly share code, notes, and snippets.

@kubek2k
Last active October 23, 2022 19:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kubek2k/8446062 to your computer and use it in GitHub Desktop.
Save kubek2k/8446062 to your computer and use it in GitHub Desktop.
SHA-256 in clojure
(defn sha256 [string]
(let [digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes string "UTF-8"))]
(apply str (map (partial format "%02x") digest))))
@kitallis
Copy link

This is wrong.

@mlapshin
Copy link

Works like a charm.

@l0st3d
Copy link

l0st3d commented Aug 27, 2019

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))))

@mlapshin
Copy link

@l0st3d OK, now it's clear. Thanks for sharing this!

@kubek2k
Copy link
Author

kubek2k commented Aug 27, 2019

@l0st3d thanks - I will update the gist according to your solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment