1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
| from __future__ import annotations
from typing import Tuple
from cryptography.hazmat.primitives.ciphers import Cipher , algorithms , modes
from cryptography.hazmat.backends import default_backend
# ==================================================
# AES-GCM-256 核心加解密(AEAD模式)
# ==================================================
def aes_gcm_encrypt(plain_data: bytes , key: bytes , nonce: bytes , ad: bytes) -> Tuple[ bytes , bytes ]:
"""GCM加密(返回密文和认证标签)"""
cipher = Cipher(algorithms.AES(key) , modes.GCM(nonce) , backend = default_backend())
encryptor = cipher.encryptor()
# 添加关联数据认证
if ad:
encryptor.authenticate_additional_data(ad)
# 加密并获取认证标签
ciphertext = encryptor.update(plain_data) + encryptor.finalize()
return ciphertext , encryptor.tag
def aes_gcm_decrypt(ciphertext: bytes , tag: bytes , key: bytes , nonce: bytes , ad: bytes) -> bytes:
"""GCM解密(带完整性验证)"""
cipher = Cipher(algorithms.AES(key) , modes.GCM(nonce , tag) , backend = default_backend())
decryptor = cipher.decryptor()
# 添加关联数据认证
if ad:
decryptor.authenticate_additional_data(ad)
# 解密(如果验证失败会抛出异常)
return decryptor.update(ciphertext) + decryptor.finalize()
if __name__ == "__main__":
# 固定输入值(实际使用中应为随机值)
plaintext = b"Secret message! AEAD is awesome!"
key = b"12345678901234567890123456789012" # 256-bit key 仅用作测试
nonce = b"123456789012" # GCM 12 字节 nonce
ad = b"Additional data" # GCM关联数据
print("\n===== AES-GCM-256 演示 =====")
print(f'原始明文数据: {plaintext.hex()}')
# GCM加密
gcm_ciphertext , tag = aes_gcm_encrypt(plaintext , key , nonce , ad)
print(f"密文数据: {gcm_ciphertext.hex()}")
print(f"认证标签: {tag.hex()}")
# GCM解密(原始数据)
gcm_decrypted = aes_gcm_decrypt(gcm_ciphertext , tag , key , nonce , ad)
print(f"正常的密文解密结果: {gcm_decrypted.decode()}, 解密成功:{gcm_decrypted.hex() == plaintext.hex()}")
# 尝试篡改密文的第一个字节
tampered_gcm_ciphertext = bytes([ gcm_ciphertext[ 0 ] ^ 0x01 ]) + gcm_ciphertext[ 1: ]
# 解密篡改后的密文 - 应该失败
try:
aes_gcm_decrypt(tampered_gcm_ciphertext , tag , key , nonce , ad)
print("解密成功 (不应该发生)")
except Exception as e:
print(f"篡改测试: {e} 解密失败,AEAD检测到密文篡改!")
# 尝试篡改关联数据
try:
aes_gcm_decrypt(gcm_ciphertext , tag , key , nonce , b"tampered_ad")
print("解密成功 (不应该发生)")
except Exception as e:
print(f"AD篡改测试: {e} 解密失败,AEAD检测到AD篡改!")
|