PC微信协议之AES-192-GCM算法

复制代码
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))
相关推荐
AllData公司负责人2 小时前
实时开发平台(Streampark)--Flink SQL功能演示
大数据·前端·架构·flink·开源
小满zs3 小时前
Next.js第五章(动态路由)
前端
灵光通码3 小时前
神经网络基本概念
python·神经网络
清沫3 小时前
VSCode debugger 调试指南
前端·javascript·visual studio code
一颗宁檬不酸3 小时前
页面布局练习
前端·html·页面布局
武子康4 小时前
Java-171 Neo4j 备份与恢复 + 预热与执行计划实战
java·开发语言·数据库·性能优化·系统架构·nosql·neo4j
无敌最俊朗@4 小时前
02-SQLite 为了防止多人同时乱写,把整个数据库文件“当一本账本加锁”
jvm·数据库·oracle
小坏讲微服务4 小时前
MaxWell中基本使用原理 完整使用 (第一章)
大数据·数据库·hadoop·sqoop·1024程序员节·maxwell
Petrichor_H_4 小时前
DAY 31 文件的规范拆分和写法
python