深入解析HPKE:从手动实现到标准库实践

基于ECDH密钥交换的HPKE运行机制说明

2025-12-26 08:59 CST  · 2147 words  · 5 min

加密的数据还能被篡改?用AEAD拯救你的数据安全

一个意想不到的实验结果 首先,我们来看一个神奇的实验: 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 from __future__ import annotations from cryptography.hazmat.primitives.ciphers import Cipher , algorithms , modes from cryptography.hazmat.primitives import padding from cryptography.hazmat.backends import default_backend # ================================================== # AES-CBC-256 核心加解密(非AEAD) # ================================================== def aes_cbc_encrypt(plain_data: bytes , key: bytes , iv: bytes) -> bytes: """CBC加密(需要PKCS7填充)""" # 添加填充 padder = padding.PKCS7(128).padder() padded_data = padder.update(plain_data) + padder.finalize() # 加密 cipher = Cipher(algorithms.AES(key) , modes.CBC(iv) , backend = default_backend()) encryptor = cipher.encryptor() return encryptor.update(padded_data) + encryptor.finalize() def aes_cbc_decrypt(ciphertext: bytes , key: bytes , iv: bytes) -> bytes: """CBC解密(无完整性验证)""" # 解密 cipher = Cipher(algorithms.AES(key) , modes.CBC(iv) , backend = default_backend()) decryptor = cipher.decryptor() padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize() # 移除填充 unpadder = padding.PKCS7(128).unpadder() return unpadder.update(padded_plaintext) + unpadder.finalize() if __name__ == "__main__": # 固定输入值(实际使用中应为随机值) plaintext = b"Transfer $100 to Alice" key = b"12345678901234567890123456789012" # 256-bit key,仅用作测试 iv = b"1234567890123456" # 16 字节 CBC IV print("===== AES-CBC-256 演示 =====") print(f'原始明文数据:{plaintext.hex()}') # CBC加密 cbc_ciphertext = aes_cbc_encrypt(plaintext , key , iv) print(f"密文: {cbc_ciphertext.hex()}") # CBC解密(原始数据) cbc_decrypted = aes_cbc_decrypt(cbc_ciphertext , key , iv) print(f"对正常的密文解密后的结果: {cbc_decrypted.hex()}, 解密成功:{cbc_decrypted.hex() == plaintext.hex()}") # 篡改第1个字节(在真实攻击中更隐蔽) # 如果改末尾的字节则可能会解填充失败,会显式的抛出异常 tampered_ciphertext = bytes([ cbc_ciphertext[ 0 ] ^ 0x01 ]) + cbc_ciphertext[ 1: ] # 解密被篡改的密文 - 不报错但得到错误结果 tampered_decrypted = aes_cbc_decrypt(tampered_ciphertext , key , iv) print( f"篡改后的密文解密出的结果: {tampered_decrypted.hex()}," f"解密成功: {tampered_decrypted.hex() == plaintext.hex()},", f"解出的数据错误但解密过程无异常") 猜一猜运行代码后会不会抛出异常? ...

2025-12-25 18:58 CST  · 2288 words  · 5 min
文章 Posts 分类 Categories 标签 Tags