在Python中,实现对称加密并添加认证(即消息完整性检查)通常涉及以下步骤:
以下是一个使用pycryptodome
库实现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字节密钥
# 加密消息
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')
# 发送加密消息和认证标签
print("Encrypted message:", ct)
print("IV:", iv)
print("Authentication tag:", auth_tag)
# 接收方使用相同的密钥和算法来解密消息并验证认证标签
# 假设接收方已知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.")
请注意,这个示例仅用于演示目的。在实际应用中,您可能需要考虑更多的安全因素,如密钥交换、加密模式的选择、填充方案等。同时,确保在实际部署中使用安全的通信协议,如TLS/SSL。