Skip to content

Instantly share code, notes, and snippets.

@cemerick
Created July 26, 2010 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cemerick/83ce26f6ad06d5bda025 to your computer and use it in GitHub Desktop.
Save cemerick/83ce26f6ad06d5bda025 to your computer and use it in GitHub Desktop.
(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