aead 模式,sm4,aes 的gcm模式,文件名:aead_apply对aead_alg 的封装 ,传入参数都是 string

"""
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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值