本篇记录使用 AES(ECB模式)+Base64 如何进行加密与解密
| 函数名称 | 函数使用注意事项 | 
| pkcs7padding() | 该方法主要用于对需要加密的明文处理因为明文 text 也必须为16字节或者16字节的倍数的字节型数据计算需要填充的字符数量并与明文拼接,从而得到符合加密规则的明文数据 | 
| AES_Encryption() | 该方法需要传入 密钥secret_key、明文text其中密钥长度和明文长度需要满足16的倍数,但一般密钥规则都是16位所以方法中传递的明文text需要调用 pkcs7padding()方法进行填充处理 | 
| AES_Decrypt() | 该方法需要传入 密钥secret_key、密文ciphertext其中密文 ciphertext 的长度要求为3的倍数因为Base64编码后的字符除了英文字母和数字外还有三个字符’ + / =‘其中’='只是为了补全编码后的字符数,所以可以用于密文填充处理 | 
示例代码如下:
import base64
from Crypto.Cipher import AES
def pkcs7padding(text):
    """明文使用PKCS7填充,padding:凑篇幅的文字 """
    need_size = 16
    text_length = len(text)
    bytes_length = len(text.encode('utf-8'))
    padding_size = text_length if (bytes_length == text_length) else bytes_length
    padding = need_size - padding_size % need_size
    padding_text = chr(padding) * padding
    return text + padding_text
def AES_Encryption(secret_key=None,text=None):
    """ AES加密 ,python运行处理的是 unicode码,因此,在做编码转换时,通常需要以unicode作为中间编码 """
    if (secret_key is None) or len(secret_key) == 0:
        secret_key = "1234567812345678"
    text =  pkcs7padding(text)
    aes = AES.new(secret_key.encode("utf-8"), AES.MODE_ECB)
    en_text = aes.encrypt(text.encode('utf-8'))
    result = str(base64.b64encode(en_text), encoding='utf-8')
    return result
def AES_Decrypt(secret_key=None, ciphertext=None):
    """AES解密,ciphertext:密文"""
    if (secret_key is None) or len(secret_key) == 0:
        secret_key = "1234567812345678"
    aes = AES.new(secret_key.encode('utf-8'), AES.MODE_ECB)
    if len(ciphertext) % 3 == 1:
        ciphertext += "==" 
    elif len(ciphertext) % 3 == 2:
        ciphertext += "="
    content = base64.b64decode(ciphertext)
    text = aes.decrypt(content).decode('utf-8')
    return text
res = AES_Encryption(secret_key="1234567812345678",text="abc我的错")
print("加密后的密文是:",res)
res = AES_Decrypt(secret_key="1234567812345678",ciphertext="iGaMr8nHU5V6UwbLYf1g5g==")
print("密文解密后的明文是:",res)