python基于base64 的AES加解密

时间:2022-01-07 15:14:47
# coding=utf-8
from Crypto.Cipher import AES
import base64

from Crypto.SelfTest.st_common import a2b_hex

'''
基于base64 的AES加密
'''
global Key
Key='XXXXXXXXXX'.encode("utf-8")

#加密
def aesEncrypt(content):
    BS = 16
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    content1=pad(content)
    text = add_to_16(content1)
    cryptos = AES.new(Key, AES.MODE_ECB)
    cipher_text = cryptos.encrypt(text)
    aes_base64 = base64.encodebytes(cipher_text)
    m=str(aes_base64, encoding="utf-8")
    return m

#解密
def aesDecrypt(text):
    unpad = lambda s: s[0:-ord(s[-1])]
    cryptos = AES.new(Key,AES.MODE_ECB)
    base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
    content=cryptos.decrypt(base64_decrypted).decode('utf-8')
    decrypted_text = unpad(content)
    decrypted_code = decrypted_text.rstrip('\0')
    return decrypted_code


# # 如果text不足16位的倍数就用空格补足为16位
def add_to_16(value):
    while len(value) % 16 != 0:
        value += '\0'
    return str.encode(value)

if __name__ == "__main__":
    '''加解密测试'''
    data = "159XXXXXXXXXX"
    encode_data = aesEncrypt(data)
    data2='NXciTUP0hHXRIHm8KEXFzBPoeDW/aWceN0fyd1VQrdc='
    decode_data = aesDecrypt(data2)
    print("data1:"+encode_data)
    print("data2:"+decode_data)