HMAC在Python3与Golang中产生不同的字符串
我有一个Golang功能,可以为给定的键和挑战计算HMAC
。 GO代码是
func get_hmac64(psk string, challenge string) string {
mac := hmac.New(sha3.New256, []byte(psk))
mac.Write([]byte(challenge))
macSum := mac.Sum(nil)
var macSumB64 = make([]byte, (len(macSum)*8+5)/6)
base64.URLEncoding.Encode(macSumB64, macSum)
return string(macSumB64)
}
我将其转换为python3如下。
def get_hmac64(self, psk: str, challenge: str) ->str:
"""
This generates a different string for same psk and challenge between Golang and Python3
"""
psk_bytes = bytes(psk, "utf-8")
challenge_bytes = bytes(challenge, "utf-8")
mac = hmac.new(psk_bytes, challenge_bytes, hashlib.sha3_256)
mac_digest = mac.digest()
b64_encoded = base64.b64decode(mac_digest)
return b64_encoded.decode("utf-8")
print(get_hmac("abc", "def"))
For the python implementation the string returned is M1P63mj5ytdYUaJJ4m2UMtEKBgRG/K3AzHCW/TjIS1k=
whereas for the Go
code the generated input for the same key and string is qWISO-QliNl_dwhDBhkd3MaT< /code>
如果键
,挑战
和hash
在HMAC
实现中保持不变,则值不应该相同。跨语言?如果是这样,我在Python翻译中错过的步骤是什么?
I have a Golang function that calculates hmac
for a given key and challenge. The go code is
func get_hmac64(psk string, challenge string) string {
mac := hmac.New(sha3.New256, []byte(psk))
mac.Write([]byte(challenge))
macSum := mac.Sum(nil)
var macSumB64 = make([]byte, (len(macSum)*8+5)/6)
base64.URLEncoding.Encode(macSumB64, macSum)
return string(macSumB64)
}
I translated this to Python3 as below.
def get_hmac64(self, psk: str, challenge: str) ->str:
"""
This generates a different string for same psk and challenge between Golang and Python3
"""
psk_bytes = bytes(psk, "utf-8")
challenge_bytes = bytes(challenge, "utf-8")
mac = hmac.new(psk_bytes, challenge_bytes, hashlib.sha3_256)
mac_digest = mac.digest()
b64_encoded = base64.b64decode(mac_digest)
return b64_encoded.decode("utf-8")
print(get_hmac("abc", "def"))
For the python implementation the string returned is M1P63mj5ytdYUaJJ4m2UMtEKBgRG/K3AzHCW/TjIS1k=
whereas for the Go
code the generated input for the same key and string is qWISO-QliNl_dwhDBhkd3MaT
Shouldnt the value be same if the key
, challenge
and the hash
remains same for the hmac
implementation across languages? If so, what is the step that I missed in the Python translation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下代码给出的结果与您针对 Python 代码报告的结果相同:(
完整代码位于 https ://go.dev/play/p/5lWG-jMfELz)。
两个区别是我使用了 sha3.New256 而不是奇怪的 NewDragonHash ,并且我通过简单地使用 .EncodeToString() 修复了 base64 编码代码>方法。
The following code gives the same results as the one you report for your Python code:
(Full code at https://go.dev/play/p/5lWG-jMfELz).
The two differences are that I used
sha3.New256
instead of the strangeNewDragonHash
, and that I fixed the base64 encoding by simply using the.EncodeToString()
method.