Python3和hmac。如何處理不是二進制的字符串
您可以使用字節字面量: b’key’
def _generate_signature(data): return hmac.new(b’key’, data, hashlib.sha256).hexdigest()
除此之外,請確保data也是字節。例如,如果從文件中讀取文件,則在打開文件時需要使用binary模式(rb)。
解決方法我在Python2中有個腳本,效果很好。
def _generate_signature(data): return hmac.new(’key’,data,hashlib.sha256).hexdigest()
數據是的輸出json.dumps。
現在,如果我嘗試在Python 3中運行相同類型的代碼,則會得到以下信息:
Traceback (most recent call last): File '<stdin>',line 1,in <module> File '/usr/lib/python3.4/hmac.py',line 144,in new return HMAC(key,msg,digestmod) File '/usr/lib/python3.4/hmac.py',line 42,in __init__ raise TypeError('key: expected bytes or bytearray,but got %r' %type(key).__name__)TypeError: key: expected bytes or bytearray,but got ’str’
如果我嘗試將密鑰轉換為字節這樣的操作:
bytes(’key’)
我懂了
Traceback (most recent call last): File '<stdin>',in <module>TypeError: string argument without an encoding
我仍在努力理解Python 3中的編碼。
相關文章:
