我从我的python实现获得的HMAC SHA1签名和我的clojure实现略有不同.我很难过会导致这种情况.
Python实现:
import hashlib import hmac print hmac.new("my-key", "my-data", hashlib.sha1).hexdigest() # 8bcd5631480093f0b00bd072ead42c032eb31059
Clojure实施:
(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
ntoskrnl.. 6
Clojure代码中将字节转换为十六进制字符串的部分会丢弃前导零.
您可以使用维护前导零("%02x"
)的格式字符串,或使用正确的十六进制编码库,例如Guava或Commons Codec.