"""
Author: tanglei
DateTime:2024-12-27 完成
微信:ciss_cedar
欢迎一起学习
加密算法:["AES","SM4"] 的GCM模式,特别适合于接口中传送数据
加密,真实性(认证),完整性 一起完成
"""
import base64
from aead_alg import MyAeadCipher, AlgName, CipherMode
code_tuple=('Hex','base64')
def aead_encrypt(key,source,aad,mode,alg_name,code=code_tuple[0]):
key = bytes.fromhex(key)
tag = None
aad=aad.encode()
source=source.encode()
my_alg = MyAeadCipher(key,aad,tag, mode, alg_name)
cipher_bytes, tag_bytes = my_alg.encrypt_bytes(source)
if code==code_tuple[0]:
cipher=cipher_bytes.hex().upper()
else:
cipher = base64.b64encode(cipher_bytes).decode()
tag=tag_bytes.hex().upper()
return cipher,tag
def aead_decrypt(key,enc_source,tag,aad,mode,alg_name,code=code_tuple[0]):
tag = bytes.fromhex(tag)
key = bytes.fromhex(key)
aad = aad.encode()
if code == code_tuple[0]:
enc_source=bytes.fromhex(enc_source)
else:
enc_source=base64.b64decode(enc_source)
my_alg = MyAeadCipher(key,aad, tag, mode, alg_name)
decrypt_bytes = my_alg.decrypt_bytes(enc_source)
source=decrypt_bytes.decode()
return source
def main():
key = '2934412A66B7A186DC35DC40E926F9EE'
source='1'
aad = '12345678'
alg_name = AlgName.AES.value
mode = CipherMode.GCM.value
# cipher, tag = aead_encrypt(key, source, aad, mode, alg_name)
# plain = aead_decrypt(key,cipher,tag,aad,mode,alg_name)
# print(f'alg_name={alg_name},mode={mode}')
# print(f'key={key},tag={tag}') # .hex().upper()
# print(f'source=', source)
# print(f'cipher={cipher}')
# print(f'plain={plain}')
code='base64'
cipher, tag = aead_encrypt(key, source, aad, mode, alg_name,code)
plain = aead_decrypt(key,cipher,tag,aad,mode,alg_name,code)
print(f'alg_name={alg_name},mode={mode},code={code}')
print(f'key={key.encode()},tag={tag.encode()}') # .hex().upper()
print(f'source=', source)
print(f'cipher={cipher}')
print(f'plain={plain}')
if __name__ == '__main__':
main()