Created
December 7, 2010 22:12
-
-
Save juergenhoetzel/732527 to your computer and use it in GitHub Desktop.
Message Digest in Clojure
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
(ns #^{:author "Jürgen Hötzel", | |
:doc "Message Digest function for Clojure | |
Usage | |
(require 'md) | |
MD5 Checksum String: | |
(md/digest-str (md/sum \"MD5\" \"/etc/passwd\")) | |
\"85dbcf75fa3eb92335cc3ac47dfa64c9\""} | |
md | |
(:import java.security.MessageDigest | |
java.io.FileInputStream | |
java.nio.ByteBuffer)) | |
(defn sum | |
"Compute message digest of a FileInputStream" | |
([#^String file] | |
(sum "MD5" file)) | |
([#^String algorithm #^String file] | |
(let [md (MessageDigest/getInstance algorithm) | |
bb (ByteBuffer/allocateDirect 8192)] | |
(with-open [channel (.getChannel (FileInputStream. file))] | |
(while (pos? (.read channel bb)) | |
(.flip bb) | |
(.update md bb) | |
(.clear bb)) | |
(.digest md))))) | |
(defn digest-str | |
[#^bytes bytes] | |
(-> (BigInteger. 1 bytes) (.toString 16))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment