Skip to content

Instantly share code, notes, and snippets.

@mikeananev
Last active June 15, 2021 17:38
Show Gist options
  • Save mikeananev/e65b27667c375bd0ad12e38115c0ac77 to your computer and use it in GitHub Desktop.
Save mikeananev/e65b27667c375bd0ad12e38115c0ac77 to your computer and use it in GitHub Desktop.
Calculate SHA3-256 sum using Clojure or Babashka
(defn digest-stream
"Calculate SHA3-256 digest for given streaming input.
Input may be: File, URI, URL, Socket, byte array, or filename as String which will be coerced to BufferedInputStream and auto closed after.
Returns digest as a byte array."
[input]
(with-open [in (clojure.java.io/input-stream input)]
(let [buf (byte-array 1024)
digest (java.security.MessageDigest/getInstance "SHA3-256")]
(loop [n (.read in buf)]
(if (<= n 0)
(.digest digest)
(recur (do (.update digest buf 0 n) (.read in buf))))))))
(defn digest-bytes->hex-string
"Returns hex string from digest bytes"
[digest-byte-array]
(apply str (map (fn [x] (format "%02x" (bit-and x 0xff))) digest-byte-array)))
(digest-bytes->hex-string (digest-stream (.getBytes "The quick brown fox jumps over the lazy dog")))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment