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)