Character encoding Clojure SHA256 HMAC函数未产生预期结果
我有以下Clojure代码:Character encoding Clojure SHA256 HMAC函数未产生预期结果,character-encoding,clojure,javax.crypto,Character Encoding,Clojure,Javax.crypto,我有以下Clojure代码: (ns myproject.hmac-sha256 (:import (javax.crypto Mac) (javax.crypto.spec SecretKeySpec))) (defn secretKeyInst [key mac] (SecretKeySpec. (.getBytes key) (.getAlgorithm mac))) (defn toString [bytes] "Convert by
(ns myproject.hmac-sha256
(:import (javax.crypto Mac)
(javax.crypto.spec SecretKeySpec)))
(defn secretKeyInst [key mac]
(SecretKeySpec. (.getBytes key) (.getAlgorithm mac)))
(defn toString [bytes]
"Convert bytes to a String"
(String. bytes "UTF-8"))
(defn sign [key string]
"Returns the signature of a string with a given
key, using a SHA-256 HMAC."
(let [mac (Mac/getInstance "HMACSHA256")
secretKey (secretKeyInst key mac)]
(-> (doto mac
(.init secretKey)
(.update (.getBytes "UTF-8")))
.doFinal
toString)))
当我在REPL中使用sign
函数时,会输出奇怪的标志符号:
(sign "key" "The quick brown fox jumps over the lazy dog")
"*��`��n�S�F�|�؏�o�r���"
而我期望的是符合以下条件的f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
这无疑是一个字符串编码问题,但我对编码知之甚少。有人能帮忙吗?若要将输出转换为可与示例进行比较的格式,请不要调用上面定义的toString,而是将.doFinal的结果视为字节数组并以十六进制打印。上面的示例是对字符串“UTF-8”而不是输入字符串进行签名:
(defn sign [key string]
"Returns the signature of a string with a given
key, using a SHA-256 HMAC."
(let [mac (Mac/getInstance "HMACSHA256")
secretKey (secretKeyInst key mac)]
(-> (doto mac
(.init secretKey)
(.update (.getBytes string)))
.doFinal)))
myproject.hmac-sha256> (apply str (map #(format "%x" %) (sign "key" "The quick brown fox jumps over the lazy dog")))
"f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
然后,您可以将toString函数编写为:
(defn toHexString [bytes]
"Convert bytes to a String"
(apply str (map #(format "%x" %) bytes)))
检查.getBytes生成的实际字节以及使用的填充。