From d5c50fca6c56645e925a33468600fe765743fbda Mon Sep 17 00:00:00 2001 From: Kiran Kulkarni Date: Mon, 16 Nov 2015 18:22:39 +0530 Subject: [PATCH] Use native Java MessageDigest for SHA-1 This change enables Ketamine to function without Apache Commons codec --- project.clj | 3 +-- src/ketamine/util.clj | 27 +++++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/project.clj b/project.clj index 77a8729..d53d739 100644 --- a/project.clj +++ b/project.clj @@ -3,5 +3,4 @@ :url "https://github.com/ghoseb/ketamine/" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} - :dependencies [[org.clojure/clojure "1.5.1"] - [commons-codec "1.8"]]) + :dependencies [[org.clojure/clojure "1.5.1"]]) diff --git a/src/ketamine/util.clj b/src/ketamine/util.clj index 3d1c547..2918f7c 100644 --- a/src/ketamine/util.clj +++ b/src/ketamine/util.clj @@ -1,14 +1,37 @@ (ns ^{:doc "Ketamine utility functions." :author "Baishampayan Ghose "} ketamine.util - (:import org.apache.commons.codec.digest.DigestUtils)) + (:require [clojure.string :as cs]) + (:import java.security.MessageDigest)) + + +(def ^:private hex [\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f]) + +(defn ^:private hexify-byte + [b] + (let [v (bit-and b 0xFF)] + [(hex (bit-shift-right v 4)) (hex (bit-and v 0x0F))])) + +(defn hexify + "Convert byte-array to hex string" + [ba] + (cs/join (mapcat hexify-byte ba))) + + +(defn sha1sum + [^String s] + {:pre [(string? s)]} + (let [digest ^MessageDigest (MessageDigest/getInstance "SHA-1")] + (.reset digest) + (hexify (.digest digest + (.getBytes ^String s "UTF-8"))))) (defn hash-code "Hash a string and convert the hash code into a number in 64 bit address space." [^String x] (-> x - DigestUtils/sha1Hex + sha1sum (subs 0 8) (Long/parseLong 16)))