赞
踩
python3
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import cryptography.exceptions
import binascii
import base64
import os
def encrypt_aes256gcm(key, ciphertext, aad):
'''
aes-256-gcm 加密
key: 为str,hex字符串,64字符(32字节)
aad: 为str,hex字符串,32字符(16字节)
ciphertext: 为bytes, 明文
返回: base64 的密文
'''
aes_gcm_ivlen = 12
key_bytes = binascii.unhexlify(key)
aad_bytes = binascii.unhexlify(aad)
data = ciphertext
iv_bytes = os.urandom(aes_gcm_ivlen)
aesgcm = AESGCM(key_bytes) # tag_length=16
crypt_bytes = aesgcm.encrypt(iv_bytes, data, aad_bytes)
return base64.b64encode(iv_bytes + crypt_bytes)
def decrypt_aes256gcm(key, ciphertext, aad):
'''
aes-256-gcm 解密
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。