AES-256-CBC 是一种对称加密算法,使用 256位密钥 和 CBC(Cipher Block Chaining)模式。它的典型使用场景包括对敏感信息进行加密存储或传输。下面是 AES-256-CBC 的加密与解密的 Python 示例,使用 pycryptodome
库:
🔧 安装库
pip install pycryptodome
✅ Python 加密与解密示例(AES-256-CBC)
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import base64# 使用256位密钥(32字节)
key = b'This_is_a_32_byte_long_secret_key!'# 加密函数
def encrypt_aes_cbc(plaintext: str, key: bytes) -> tuple:iv = get_random_bytes(16) # CBC模式需要16字节IVcipher = AES.new(key, AES.MODE_CBC, iv)ciphertext = cipher.encrypt(pad(plaintext.encode('utf-8'), AES.block_size))return base64.b64encode(iv + ciphertext).decode('utf-8') # 返回Base64编码的字符串# 解密函数
def decrypt_aes_cbc(ciphertext_b64: str, key: bytes) -> str:raw = base64.b64decode(ciphertext_b64)iv = raw[:16]ciphertext = raw[16:]cipher = AES.new(key, AES.MODE_CBC, iv)plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)return plaintext.decode('utf-8')# 示例
plain_text = "Hello, AES 256 CBC!"
encrypted = encrypt_aes_cbc(plain_text, key)
decrypted = decrypt_aes_cbc(encrypted, key)print("原文:", plain_text)
print("加密后:", encrypted)
print("解密后:", decrypted)
📌 注意事项
- 密钥必须是32字节(256位),你可以用密码哈希(如 SHA256)生成它。
- IV必须是16字节,每次加密都要使用新的随机IV。
- 加密结果中我们将
IV + ciphertext
合并后 base64 编码,以便传输或存储。
🔐 若你有已知密钥和IV的情况
如果你已经有指定的密钥和 IV(比如前端加密传来的),你可以这样使用:
iv = bytes.fromhex('00112233445566778899aabbccddeeff')
key = bytes.fromhex('000102030405060708090a0b0c0d0e0f' * 2)
cipher = AES.new(key, AES.MODE_CBC, iv)