Python 中的訊息認證金鑰雜湊
使用 Python 中的加密雜湊函式進行訊息認證可以透過 HMAC 機制實現。我們可以將 HMAC 與多個可迭代的雜湊函式(如 MD5、SHA-1)結合一個共享金鑰一起使用。
基本思想是透過生成實際資料與共享金鑰組合的加密雜湊來保護我們的資料。最終結果在不包含金鑰的情況下發送,但生成的雜湊值可用於檢查傳輸或儲存的訊息。
語法
hmac.new(key, msg = None, digestmod = None)
返回一個生成新的 hmac 物件。
其中 -
Key – 這裡的共享金鑰。
Msg – 要雜湊的訊息,這裡是要雜湊的訊息
Digestmod – HMAC 物件要使用的摘要名稱或模組
HMAC 模組的方法和屬性 -
hmac.update(message)
用於使用給定訊息更新 hmac 物件。如果多次呼叫此方法,訊息將被追加。
hmac.digest()
返回迄今為止傳遞給 update() 方法的位元組的摘要。
hashlib.hexdigest()
與 digest() 相同,只是摘要作為長度的兩倍的字串返回,僅包含十六進位制數字。這可用於在電子郵件或其他非二進位制環境中安全地交換值。
haslib.copy()
返回 hmac 物件的副本(“克隆”)。
示例 1
使用預設的 MD5 雜湊演算法建立雜湊。
#Import libraries import hashlib import hmac #data update_bytes = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit. \ Suspendisse tristique condimentum viverra. Nulla accumsan \ orci risus, non congue lacus feugiat id.' #secret key password = b'402xy5#' #Generate cryptographic hash using md5 my_hmac = hmac.new(update_bytes, password, hashlib.md5) print("The first digest: " + str(my_hmac.digest())) print("The Canonical Name: " + my_hmac.name) print("Block size: " + str (my_hmac.block_size) + "bytes") print("Digest size: " + str(my_hmac.digest_size) + "bytes") #Create a copy of the hmac object my_hmac_cpy = my_hmac.copy() print("The Copied digest: " + str(my_hmac_cpy.digest()))
輸出
The first digest: b'H\xcc.nf\xdd\x8bC\x8di\x0cC\xb8\xe9l\xa8' The Canonical Name: hmac-md5 Block size: 64bytes Digest size: 16bytes The Copied digest: b'H\xcc.nf\xdd\x8bC\x8di\x0cC\xb8\xe9l\xa8'
由於 SHA1 比 MD5 演算法更安全,如果您考慮使用 SHA1 演算法執行上述程式。只需在此行中修改演算法名稱,
my_hmac = hmac.new(update_bytes, password,hashlib.sha1)
我們的結果將類似於
第一個摘要:b'\xc3T\xe7[\xc8\xa3O/$\xbd`A\xad\x07d\xe8\xae\xa2!\xb4'
The Canonical Name: hmac-sha1 Block size: 64bytes Digest size: 20bytes The Copied digest: b'\xc3T\xe7[\xc8\xa3O/$\xbd`A\xad\x07d\xe8\xae\xa2!\xb4'
應用
HMAC 身份驗證機制可用於任何重視安全性的場所,例如公共網路服務。例如,在公共網路中,我們透過管道或套接字傳送重要的檔案/資料,該檔案/資料應先進行簽名,然後在使用資料之前測試簽名。