Commits

Miki Tebeka committed 0897b8c

Initial import

Comments (0)

Files changed (3)

+(defproject digest "1.0.0-SNAPSHOT"
+  :description "Digest algorithms (MD5, SHA ...) for Clojure"
+  :dependencies [[org.clojure/clojure "1.2.0"]])
+(ns digest
+  #^{ :author "Miki Tebeka <miki.tebeka@gmail.com>"
+      :doc "Message digest algorithms for Clojure"}
+  (:use [clojure.string :only (split lower-case)])
+  (:import (java.security MessageDigest Security)))
+
+; Code "borrowed" from http://www.holygoat.co.uk/blog/entry/2009-03-26-1
+
+(defmulti digest (fn [_ m] (class m)))
+
+(defmethod digest String [algorithm message]
+  (digest algorithm [message]))
+
+(defmethod digest :default
+  [algorithm messages]
+  (let [algo (MessageDigest/getInstance algorithm)]
+    (.reset algo)
+    (dorun (map #(.update algo (.getBytes %)) messages))
+    (.toString (BigInteger. 1 (.digest algo)) 16)))
+
+(defn algorithms []
+  "List support digest algorithms"
+  (let [providers (into [] (Security/getProviders))
+        names (mapcat #(enumeration-seq (.keys %)) providers)
+        digest-names (filter #(re-find #"MessageDigest\.[A-Z0-9-]+$" %) names)]
+    (set (map #(last (split % #"\.")) digest-names))))
+
+
+(defn create-fns []
+  "Create utility function for each digest algorithms"
+  (dorun (map #(intern 'digest (symbol (lower-case %)) (partial digest %))
+              (algorithms))))
+(create-fns)

test/digest_test.clj

+(ns digest-test
+  (:use [digest] :reload-all)
+  (:use [clojure.test]))
+
+(deftest md5-test
+  (is (= (digest "md5" "foo") "acbd18db4cc2f85cedef654fccc4a4d8")))
+
+
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.