The part of your Clojure code that translates bytes to hex strings drops leading zeros.
You could use a format string that maintains a leading zero ("%02x"
), or use a proper hex encoding library, such as Guava or Commons Codec.
题
The HMAC SHA1 signatures I'm getting from my python implementation and my clojure implementation are slightly different. I'm stumped as to what would cause that.
Python implementation:
import hashlib
import hmac
print hmac.new("my-key", "my-data", hashlib.sha1).hexdigest() # 8bcd5631480093f0b00bd072ead42c032eb31059
Clojure implementation:
(ns my-project.hmac
(:import (javax.crypto Mac)
(javax.crypto.spec SecretKeySpec)))
(def algorithm "HmacSHA1")
(defn return-signing-key [key mac]
"Get an hmac key from the raw key bytes given some 'mac' algorithm.
Known 'mac' options: HmacSHA1"
(SecretKeySpec. (.getBytes key) (.getAlgorithm mac)))
(defn sign-to-bytes [key string]
"Returns the byte signature of a string with a given key, using a SHA1 HMAC."
(let [mac (Mac/getInstance algorithm)
secretKey (return-signing-key key mac)]
(-> (doto mac
(.init secretKey)
(.update (.getBytes string)))
.doFinal)))
; Formatting
(defn bytes-to-hexstring [bytes]
"Convert bytes to a String."
(apply str (map #(format "%x" %) bytes)))
; Public functions
(defn sign-to-hexstring [key string]
"Returns the HMAC SHA1 hex string signature from a key-string pair."
(bytes-to-hexstring (sign-to-bytes key string)))
(sign-to-hexstring "my-key" "my-data") ; 8bcd563148093f0b0bd072ead42c32eb31059
解决方案
The part of your Clojure code that translates bytes to hex strings drops leading zeros.
You could use a format string that maintains a leading zero ("%02x"
), or use a proper hex encoding library, such as Guava or Commons Codec.