Python3和hmac。如何處理不是二進(jìn)制的字符串
您可以使用字節(jié)字面量: b’key’
def _generate_signature(data): return hmac.new(b’key’, data, hashlib.sha256).hexdigest()
除此之外,請(qǐng)確保data也是字節(jié)。例如,如果從文件中讀取文件,則在打開(kāi)文件時(shí)需要使用binary模式(rb)。
解決方法我在Python2中有個(gè)腳本,效果很好。
def _generate_signature(data): return hmac.new(’key’,data,hashlib.sha256).hexdigest()
數(shù)據(jù)是的輸出json.dumps。
現(xiàn)在,如果我嘗試在Python 3中運(yùn)行相同類型的代碼,則會(huì)得到以下信息:
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’
如果我嘗試將密鑰轉(zhuǎn)換為字節(jié)這樣的操作:
bytes(’key’)
我懂了
Traceback (most recent call last): File '<stdin>',in <module>TypeError: string argument without an encoding
我仍在努力理解Python 3中的編碼。
相關(guān)文章:
1. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案2. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單3. chat.asp聊天程序的編寫(xiě)方法4. 輕松學(xué)習(xí)XML教程5. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向6. 使用XSL將XML文檔中的CDATA注釋輸出為HTML文本7. 小技巧處理div內(nèi)容溢出8. PHP循環(huán)與分支知識(shí)點(diǎn)梳理9. XML入門(mén)的常見(jiàn)問(wèn)題(一)10. css進(jìn)階學(xué)習(xí) 選擇符
