Thu 26 Mar 2009

MD5 in Clojure

A side project in which I am engaging involved generating MD5 sums from strings in Clojure. Here's the code; it's partially cribbed from Java examples on the net, so it's only right I throw it back out.

(ns uk.co.holygoat.util.md5
  (:refer-clojure)
  (:import
     (java.security 
       NoSuchAlgorithmException
       MessageDigest)
     (java.math BigInteger)))

(defn md5-sum
  "Compute the hex MD5 sum of a string."
  [#^String str]
  (let [alg (doto (MessageDigest/getInstance "MD5")
              (.reset)
              (.update (.getBytes str)))]
    (try
      (.toString (new BigInteger 1 (.digest alg)) 16)
      (catch NoSuchAlgorithmException e
        (throw (new RuntimeException e))))))

Posted at 2009-03-26 07:16:00 by Richard NewmanLink to MD5 in Clojure