Jun
28
md5 hash from a file in Clojure

Here’s a simple function to compute the md5 hash (in hexadecimal string form) of a file on the filesystem:

1
2
3
4
5
6
7
8
9
10
11
(defn md5sum
  "Returns the md5 hash of the contents of file (where file is a File,
   a FileDescriptor or a String with the file's path"

  [file]
  (let [input (java.io.FileInputStream. file)
        digest (java.security.MessageDigest/getInstance "MD5")
        stream (java.security.DigestInputStream. input digest)
        bufsize (* 1024 1024)
        buf (byte-array bufsize)]
    (while (not= -1 (.read stream buf 0 bufsize)))
    (apply str (map (partial format "%02x") (.digest digest)))))

filed under: clojure | permalink |

© 2012 Gertalot — Theme based on WP Bipolar by ThemeLab — Powered by Wordpress