问题
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