Clojure and MessageDigest
June 22nd, 2009
Last night I needed a quick and dirty SHA function for a clojure-based web application. MessageDigest to the rescue!
(ns com.deskchecked.utils
(:use clojure.contrib.str-utils)
(:import [java.security MessageDigest]))
(defn sha
"Generates a SHA-256 hash of the given input plaintext."
[input]
(let [md (MessageDigest/getInstance "SHA-256")]
(. md update (.getBytes input))
(let [digest (.digest md)]
(str-join "" (map #(Integer/toHexString (bit-and % 0xff)) digest)))))
There’s obviously a dependency on clojure-contrib here which you can do away with if you don’t need it. And of course, you can pick a hashing algorithm to suit your needs.
Nothing exciting, but I figure I can’t be the only person in need of this sort of stuff.
Categories: Functional Programming, Software Development |


