Skip to content

Instantly share code, notes, and snippets.

@cemerick cemerick/hash_of.clj Secret
Created Jul 26, 2010

Embed
What would you like to do?
(defmulti hash-of
"Returns a string representation of a SHA1 hash of the provided data, which can be
a File, byte[], String (which will be converted to UTF-8 byte[]), or an InputStream."
class)
(defmethod hash-of String
[#^String s]
(hash-of (.getBytes s "UTF-8")))
(defmethod hash-of (class (make-array Byte/TYPE 0))
[bytes]
(hash-of (java.io.ByteArrayInputStream. bytes)))
(defmethod hash-of java.io.File
[#^java.io.File f]
(-> f java.io.FileInputStream. java.io.BufferedInputStream. hash-of))
(defmethod hash-of java.io.InputStream
[#^java.io.InputStream is]
(let [digest (MiscUtilities/createDigester "SHA1")
arr (make-array Byte/TYPE 2048)]
(loop [len (.read is arr)]
(when-not (== -1 len)
(.update digest arr 0 len)
(recur (.read is arr))))
(-> digest .digest MiscUtilities/toHex)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.