在Python中,實現(xiàn)對稱加密并添加認證(即消息完整性檢查)通常涉及以下步驟:
以下是一個使用pycryptodome
庫實現(xiàn)AES對稱加密和HMAC認證的示例:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from Crypto.Hash import HMAC
import base64
# 生成隨機密鑰
key = get_random_bytes(16) # AES-128需要16字節(jié)密鑰
# 加密消息
message = b"Hello, world!"
cipher = AES.new(key, AES.MODE_CBC)
ct_bytes = cipher.encrypt(pad(message, AES.block_size))
iv = base64.b64encode(cipher.iv).decode('utf-8')
ct = base64.b64encode(ct_bytes).decode('utf-8')
# 生成HMAC認證標簽
hmac = HMAC.new(key, digestmod=hashlib.sha256)
hmac.update(ct_bytes)
auth_tag = base64.b64encode(hmac.digest()).decode('utf-8')
# 發(fā)送加密消息和認證標簽
print("Encrypted message:", ct)
print("IV:", iv)
print("Authentication tag:", auth_tag)
# 接收方使用相同的密鑰和算法來解密消息并驗證認證標簽
# 假設(shè)接收方已知iv和auth_tag
received_ct = base64.b64decode(ct)
received_iv = base64.b64decode(iv)
received_auth_tag = base64.b64decode(auth_tag)
cipher = AES.new(key, AES.MODE_CBC, received_iv)
pt = unpad(cipher.decrypt(received_ct), AES.block_size)
hmac = HMAC.new(key, digestmod=hashlib.sha256)
hmac.update(received_ct)
calculated_auth_tag = base64.b64encode(hmac.digest()).decode('utf-8')
if calculated_auth_tag == received_auth_tag:
print("Message integrity verified.")
print("Decrypted message:", pt.decode('utf-8'))
else:
print("Message integrity check failed.")
請注意,這個示例僅用于演示目的。在實際應用中,您可能需要考慮更多的安全因素,如密鑰交換、加密模式的選擇、填充方案等。同時,確保在實際部署中使用安全的通信協(xié)議,如TLS/SSL。