Python中实现AES加密

26 阅读1分钟

在Python中实现AES加密,我们可以使用内置的cryptography库。

安装cryptography

pip install pycryptodome

示例如下

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
import base64


def aes_salt(message):
    # 原始消息,这里假设它是一个数字字符串
    key = 密钥  # 密钥,需要是16、24或32字节长
    mode = AES.MODE_ECB  # 使用ECB模式

    # 创建加密对象
    cryptor = AES.new(key.encode('utf-8'), mode)

    # 使用pad函数填充数据,使其长度为16的倍数
    padded_message = pad(message.encode('utf-8'), AES.block_size)

    # 加密消息
    ciphertext = cryptor.encrypt(padded_message)

    # 将加密后的数据转换为base64编码
    encoded_cipher = base64.b64encode(ciphertext)
    print(encoded_cipher.decode('utf-8'))
    return encoded_cipher.decode('utf-8')