import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes

# 定义加密函数
def aes_cbc_encrypt_base64(plaintext, key):
"""
AES-CBC 模式加密,并返回 Base64 编码的加密结果
:param plaintext: 明文字符串
:param key: 16, 24 或 32 字节的密钥
:return: Base64 编码的加密数据(IV + 密文)
"""
iv = get_random_bytes(16) # 生成随机 IV
cipher = AES.new(key, AES.MODE_CBC, iv) # 创建 AES 加密对象
ciphertext = cipher.encrypt(pad(plaintext.encode(), AES.block_size)) # 填充并加密
encrypted_data = iv + ciphertext # 将 IV 和密文拼接
return base64.b64encode(encrypted_data).decode() # 转换为 Base64 编码并返回

# 定义解密函数
def aes_cbc_decrypt_base64(encrypted_data_base64, key):
"""
解密 Base64 编码的 AES-CBC 加密数据
:param encrypted_data_base64: Base64 编码的加密数据(IV + 密文)
:param key: 16, 24 或 32 字节的密钥
:return: 解密后的明文字符串
"""
encrypted_data = base64.b64decode(encrypted_data_base64) # 解码 Base64
iv = encrypted_data[:16] # 提取前 16 字节作为 IV
ciphertext = encrypted_data[16:] # 提取剩余部分作为密文
cipher = AES.new(key, AES.MODE_CBC, iv) # 创建 AES 解密对象
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size) # 解密并去除填充
return plaintext.decode()

# 示例代码
if name == "main":
# 使用 16 字节密钥(可以改为 24 或 32 字节)
key = b"ThisIsA16ByteKey"

# 明文
plaintext = "Hello, this is a secret message!"

# 加密
encrypted_data_base64 = aes_cbc_encrypt_base64(plaintext, key)
print(f"Encrypted (Base64): {encrypted_data_base64}")

# 解密
decrypted_data = aes_cbc_decrypt_base64(encrypted_data_base64, key)
print(f"Decrypted: {decrypted_data}")
 
 
Back to Top