Python3和hmac。如何處理不是二進(jìn)制的字符串
您可以使用字節(jié)字面量: b’key’
def _generate_signature(data): return hmac.new(b’key’, data, hashlib.sha256).hexdigest()
除此之外,請(qǐng)確保data也是字節(jié)。例如,如果從文件中讀取文件,則在打開文件時(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. python共軛梯度法特征值迭代次數(shù)討論2. 利用FastReport傳遞圖片參數(shù)在報(bào)表上展示簽名信息的實(shí)現(xiàn)方法3. H5頁(yè)面使用audio標(biāo)簽播放音頻4. ASP.NET MVC視圖頁(yè)使用jQuery傳遞異步數(shù)據(jù)的幾種方式詳解5. CSS3使用過(guò)度動(dòng)畫和緩動(dòng)效果案例講解6. ASP.NET MVC通過(guò)勾選checkbox更改select的內(nèi)容7. react axios 跨域訪問(wèn)一個(gè)或多個(gè)域名問(wèn)題8. 詳解php如何合并身份證正反面圖片為一張圖片9. AJAX實(shí)現(xiàn)省市縣三級(jí)聯(lián)動(dòng)效果10. XHTML 1.0:標(biāo)記新的開端
