這邊 用簡單的 Sample Code 說明 如何用 python hmac 物件產生 SHA-256 的數位電子簽章(Signature)
首先我們要知道 電子簽章 就是 利用 HASH 雜湊函數(SHA-256) 將 一段明文內容 透過個人私鑰加密後 所產生的 Binary或16進制 摘要(Digest) 再用 Base64 編碼 成 可在網路上任意傳輸的字串. 由於有個人私鑰元素,所以才能成為識別該內容為某人所傳輸的 數位電子簽章.
因此,python 提供了 hmac 模組 來產生 hash 物件,同時需要引用 base64 和 hashlib的sha256 模組 來生成 Signature:
import hmac
import base64
from hashlib import sha256
接著 我們需要一個私鑰 key 來 加密雜湊 我們的 message:
key = "abcd1234"
message = "my lover is only you"
這邊 我們要先把 key&message 透過 utf-8 編碼成 Binary 物件 才能傳入 hmac.new method 雜湊成 sha256 物件 sha :
# hmac.new will new a hash object that encrypts message with a secret key and a hash mothed(digestmod)
# messqge and secret need to be byte type.
bkey = key.encode('utf-8')
bmessage = message.encode('utf-8')
sha = hmac.new(bkey, bmessage, digestmod=sha256)
產生 sha256 物件之後, 我們便可以透過其 digest/hexdigest method 來列印出 key與message 雜湊之後產生的摘要(digest) , 差別只在於 digest()是 純 binary format 而 hexdigest() 則是 16進制的 binary format:
#digest() method will return the byte code of a hash object.
#hexdigest() method will return the hex code of a hash object.
print("Sha-256 Binary Digest: %s"%sha.digest())
print("Sha-256 Hex Digest: %s"%sha.hexdigest())
最後 我們透過 base64.b64encode 函數 把 sha256 內容摘要編碼成 base64的可傳輸二進制base64編碼字串, 這個字串就是我們在網路上跟隨message傳給接收者的電子簽章signature:
#for delivery hash code via network, we need to transform it into a base64 string format.
signature= base64.b64encode(sha.digest())
print("Secret Key = %s"%key)
print("Message = %s"%message)
print("SHA-256 Signature: %s"%signature)
執行結果:
[Source Code]
2022年12月29日星期四