Python HMAC / Encoding in 3.x vs 2.x

浪子不回头ぞ 提交于 2019-12-23 02:30:46

问题


I'm working with code that works in Python 2.7, but when I use it with 3.6, it doesn't work. It's meant to encode a signature for an Amazon MWS API call.

The original code in Python 2.7:

sig_encoded = base64.b64encode(hmac.new(str(self.secret_key), sig_data, hashlib.sha256).digest())

I read a few other posts here, followed the instructions, and came up with this:

Python 3.6

    key_enc = (bytes(self.secret_key, "utf-8"))
    sig_data_enc = (bytes(sig_data, "utf-8"))
    sig_encoded =  base64.b64encode(hmac.new(key_enc, sig_data_enc, hashlib.sha256).digest())

However, this returns an error from the API. What is wrong with the version used in Python 3.6?

Thanks!


回答1:


I was able to find the answer. The code that works in Python 3.6 is:

return base64.b64encode(
        hmac.new(str(self.secret_key).encode('utf-8'), sig_data.encode('utf-8'), hashlib.sha256).digest())


来源:https://stackoverflow.com/questions/40646375/python-hmac-encoding-in-3-x-vs-2-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!