Created
December 18, 2012 07:14
-
-
Save jizhang/4325757 to your computer and use it in GitHub Desktop.
Clojure - Calculate MD5 hash of a given string.
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
(import 'java.security.MessageDigest | |
'java.math.BigInteger) | |
(defn md5 [s] | |
(let [algorithm (MessageDigest/getInstance "MD5") | |
size (* 2 (.getDigestLength algorithm)) | |
raw (.digest algorithm (.getBytes s)) | |
sig (.toString (BigInteger. 1 raw) 16) | |
padding (apply str (repeat (- size (count sig)) "0"))] | |
(str padding sig))) | |
; for full digest support, use clj-digest: https://github.com/tebeka/clj-digest |
Is it possible to get back the raw bytes from the md5 String "%032x"
format?
Simply doing "f47c75614087a8dd938ba4acff252494".getBytes()
does not produce the same result as the digested raw byte[].
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For a version that works on anything extended with
clojure.java.io/IOFactory
(likeFile
):Still has the disadvantage of reading the whole file into a byte array at once though. If that's a concern for anyone I think there are some pretty simple solutions here: https://stackoverflow.com/questions/304268/getting-a-files-md5-checksum-in-java