Python 中的 AES 加密和解密操作
1. 加密原理
Python 中使用 pycryptodome
库来实现 AES 加密。它同样基于对称密钥对数据进行加密。数据先被填充为 16 字节的倍数,然后通过 AES 算法的加密操作将明文转换为密文。
2. 代码示例
from Crypto.Cipher import AES
import base64
def aes_encrypt(plaintext, key):
# 填充明文为16字节的倍数
padded_plaintext = plaintext + (16 - len(plaintext) % 16) * chr(16 - len(plaintext) % 16)
# 创建AES加密对象,使用ECB模式
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# 执行加密操作
encrypted_bytes = cipher.encrypt(padded_plaintext.encode('utf-8'))
# 将加密后的字节数组转换为Base64编码的字符串
return base64.b64encode(encrypted_bytes).decode('utf-8')
def aes_decrypt(encrypted_text, key):
# 创建AES解密对象,使用ECB模式
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# 对Base64编码的密文进行解码
encrypted_bytes = base64.b64decode(encrypted_text)
# 执行解密操作
decrypted_bytes = cipher.decrypt(encrypted_bytes)
# 去除填充的数据
unpadded_text = decrypted_bytes[:-decrypted_bytes[-1]].decode('utf-8')
return unpadded_text
# 测试代码
plaintext = "Hello, Python!"
key = "///aes.golong.uk"
encrypted_text = aes_encrypt(plaintext, key)
print("加密后的文本:", encrypted_text)
decrypted_text = aes_decrypt(encrypted_text, key)
print("解密后的文本:", decrypted_text)
3. 代码解释
- 定义了加密函数 aes_encrypt
和解密函数 aes_decrypt
。
- 在加密函数中,首先对明文进行填充,使其长度为 16 字节的倍数。然后使用 AES.new
方法创建 AES 加密对象,指定密钥和加密模式(这里是 ECB
)。接着对填充后的明文进行加密,得到加密后的字节数组,最后将其转换为 Base64 编码的字符串。
- 在解密函数中,同样创建 AES 解密对象,对 Base64 解码后的密文进行解密,然后去除填充的数据,得到原始的明文。
- 在线校验密文是否与明文一致。 AES在线加密