簡體   English   中英

Python 腳本加密消息失敗

[英]Python script to encrypt a message fails

嘗試通過給我的腳本一個密鑰和消息來加密到 HMAC-SHA256。

我在網上看到的一個流行示例無法在我的機器上運行:

import hmac
import hashlib
import binascii

def create_sha256_signature(key, message):
    byte_key = binascii.unhexlify(key)
    message = message.encode()
    enc = hmac.new(byte_key, message, hashlib.sha256).hexdigest().upper()
    print (enc)

create_sha256_signature("KeepMySecret", "aaaaa")

為什么我會收到此錯誤?

Traceback (most recent call last):
  File "encryption.py", line 12, in <module>
    create_sha256_signature("SaveMyScret", "aaaaa")
  File "encryption.py", line 8, in create_sha256_signature
    byte_key = binascii.unhexlify(key)
binascii.Error: Odd-length string

我應該如何更改我的代碼,以便我能夠提供自己的快捷鍵?

當您調用unhexlify時,這意味着您的key是字節的十六進制表示。 例如A73FB0FF... 在這種編碼中,每個字符只代表 4 位,因此一個字節需要兩個字符,整個輸入字符串需要偶數個字符。

文檔

hexstr 必須包含偶數個十六進制數字

但實際上給定的秘密“SaveMySecret”或“KeepMySecret 不僅有奇數個字符,而且甚至不是有效的十六進制代碼,所以無論如何它都會失敗:

binascii.Error:找到非十六進制數字

您可以提供十六進制編碼形式的密鑰,也可以使用類似的東西而不是調用unhexlify

byte_key = key.encode('utf-8')

獲取字節作為hmac.new()的輸入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM