Python实现AES加密解密示例代码详解
python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
import base64
# AES 加密函数
def aes_encrypt(plaintext, key):
# 生成随机初始化向量 (IV)
iv = get_random_bytes(AES.block_size)
# 创建 AES-CBC 加密器
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv)
# 对明文进行 PKCS7 填充并加密
ciphertext = cipher.encrypt(pad(plaintext.encode('utf-8'), AES.block_size))
# 将 IV 和密文拼接后进行 Base64 编码
return base64.b64encode(iv + ciphertext).decode('utf-8')
# AES 解密函数
def aes_decrypt(ciphertext_b64, key):
# 解码 Base64 并分离 IV 和密文
ciphertext = base64.b64decode(ciphertext_b64)
iv = ciphertext[:AES.block_size]
ciphertext_body = ciphertext[AES.block_size:]
# 创建 AES-CBC 解密器
cipher = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv)
# 解密并去除填充
plaintext = unpad(cipher.decrypt(ciphertext_body), AES.block_size)
return plaintext.decode('utf-8')
# 使用示例
if __name__ == "__main__":
# 注意:AES-256 需要 32 字节密钥,AES-128 需要 16 字节密钥
secret_key = "thisisaverysecretkey" # 建议实际使用时使用更安全的密钥管理方式
original_text = "Hello, AES Encryption!"
print("原始文本:", original_text)
# 加密
encrypted = aes_encrypt(original_text, secret_key)
print("加密后:", encrypted)
# 解密
decrypted = aes_decrypt(encrypted, secret_key)
print("解密后:", decrypted)
重要说明:
依赖安装:需要先安装 pycryptodome 库
bash
pip install pycryptodome
密钥管理:
示例中使用的是固定字符串密钥,实际生产环境应使用安全的密钥管理方案
AES-256 需要 32 字节密钥,AES-128 需要 16 字节密钥(示例为 AES-128)
加密模式:
使用 CBC 模式(需要 IV)
每次加密都会生成随机 IV,提高安全性
IV 会与密文一起存储(前 16 字节)
数据填充:
使用 PKCS7 填充方案
自动处理数据长度对齐问题
编码方式:
最终结果使用 Base64 编码,便于存储和传输
输出示例:
原始文本: Hello, AES Encryption!
加密后: 4sJ8aW7l3XyV2kMz6NQx1A==…(具体输出每次不同)
解密后: Hello, AES Encryption!
原始文本:apt/bv6RF6pDYsdXJaukyKzoq9/3qcdlkGcSzd2+KedJelM=/apt
作者:2401_90021373