久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

Python3和hmac。如何處理不是二進(jìn)制的字符串

瀏覽:27日期:2022-08-07 13:30:42
如何解決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中的編碼。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 榆社县| 巨鹿县| 济宁市| 三明市| 横山县| 托克逊县| 历史| 长沙县| 西峡县| 乌兰察布市| 建阳市| 南皮县| 荥经县| 秭归县| 肥乡县| 静宁县| 海宁市| 玉树县| 镇江市| 阿图什市| 霍州市| 蕉岭县| 平谷区| 亳州市| 城口县| 清涧县| 阜新| 武乡县| 湟源县| 张家川| 黔南| 清涧县| 临武县| 婺源县| 蒙城县| 乐东| 长汀县| 洛南县| 桦甸市| 武威市| 龙川县|