我有以下 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 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)))
当我sign
在 REPL 中使用该函数时,会输出奇怪的字形:
(sign "key" "The quick brown fox jumps over the lazy dog")
"*��`��n�S�F�|�؏�o�r���"
而我期望f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8
按照https://en.wikipedia.org/wiki/Hash-based_message_authentication_code#Examples_of_HMAC_.28MD5.2C_SHA1.2C_SHA256.29
这无疑是一个字符串编码问题,但我对编码知之甚少。任何人都可以帮忙吗?