from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import constant_time
from cryptography.hazmat.backends import default_backend
import os
import binascii
# ===============================
# AES-192-GCM 加密函数
# ===============================
def aes_192_gcm_encrypt(key: bytes, plaintext: bytes, associated_data: bytes = b""):
"""
使用 AES-192-GCM 进行加密
:param key: 24 字节密钥
:param plaintext: 明文数据
:param associated_data: 附加认证数据(可选)
:return: (nonce, ciphertext, tag)
"""
if len(key) != 24:
raise ValueError("AES-192 需要 24 字节密钥")
# 生成 12 字节随机 nonce(GCM 推荐长度)
nonce = os.urandom(12)
encryptor = Cipher(
algorithms.AES(key),
modes.GCM(nonce),
backend=default_backend()
).encryptor()
# 添加 AAD(可选)
encryptor.authenticate_additional_data(associated_data)
# 执行加密
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
# 返回 nonce、密文、tag
return nonce, ciphertext, encryptor.tag
# ===============================
# AES-192-GCM 解密函数
# ===============================
def aes_192_gcm_decrypt(key: bytes, nonce: bytes, tag: bytes, ciphertext: bytes, associated_data: bytes = b""):
"""
使用 AES-192-GCM 进行解密
:param key: 24 字节密钥
:param nonce: 加密时的随机 nonce
:param tag: GCM 认证标签
:param ciphertext: 密文数据
:param associated_data: 附加认证数据(可选)
:return: plaintext
"""
decryptor = Cipher(
algorithms.AES(key),
modes.GCM(nonce, tag),
backend=default_backend()
).decryptor()
decryptor.authenticate_additional_data(associated_data)
# 执行解密
plaintext = decryptor.update(ciphertext) + decryptor.finalize()
return plaintext
# ===============================
# 示例测试
# ===============================
if __name__ == "__main__":
key_hex = "35FE9BD1DFF7FD1939382935F4AEEF62E2C7895D8F441305"
key = bytes.fromhex(key_hex)
plaintext = b"Hello, AES-192-GCM Encryption!"
aad = b"optional_authenticated_data"
print("原文:", plaintext)
# 加密
nonce, ciphertext, tag = aes_192_gcm_encrypt(key, plaintext, aad)
print("Nonce:", nonce.hex())
print("Ciphertext:", ciphertext.hex())
print("Tag:", tag.hex())
# 解密
decrypted = aes_192_gcm_decrypt(key, nonce, tag, ciphertext, aad)
print("解密结果:", decrypted)
# 校验
print("是否一致:", constant_time.bytes_eq(plaintext, decrypted))
PC微信协议之AES-192-GCM算法
AiXed2025-11-17 2:04
相关推荐
Warson_L1 小时前
高性能架构设计databook2 小时前
新数据到手,先跑哪几步检查czq_26867194873 小时前
Python打卡第46天卸任3 小时前
Vibe coding工具使用心得brien93 小时前
为什么模型标称 1M,Google Antigravity 聊到 256K 却突然失忆?我们给它做了个原生行内监控圆环修炼的dance4 小时前
录屏关键帧间隔多少合适?六档实测,2秒到10秒小了75.6%Lank_M4 小时前
关键帧从1秒拉到10秒,录屏小87.3%,摄像头小10.8%补码缩写4 小时前
用 ffprobe 拆录屏,八成字节在 29 个关键帧上百思不得小李4 小时前
一个复杂的动态表单是如何实现的Flynt4 小时前
日涨4000星的OSINT工具,我拿Linus的用户名和一个随机字符串实测了一遍