Mã hóa AES
Các hàm hỗ trợ mã hóa và giải mã AES-256-CBC bằng thư viện cryptography của Python. IV được nối vào đầu ciphertext và lưu dưới dạng chuỗi hex.
import os
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from cryptography.hazmat.backends import default_backend
def aes_decrypt(encrypted: str, key: bytes) -> str:
ciphertext = binascii.unhexlify(encrypted)
if len(ciphertext) < 16:
raise ValueError("ciphertext too short")
iv = ciphertext[:16]
ciphertext = ciphertext[16:]
if len(ciphertext) % 16 != 0:
raise ValueError("ciphertext is not a multiple of block size")
cipher = Cipher(
algorithms.AES(key),
modes.CBC(iv),
backend=default_backend()
)
decryptor = cipher.decryptor()
padded_plain = decryptor.update(ciphertext) + decryptor.finalize()
unpadder = padding.PKCS7(128).unpadder()
plain_bytes = unpadder.update(padded_plain) + unpadder.finalize()
return plain_bytes.decode()
def aes_encrypt(plain: str, key: bytes) -> str:
cipher = Cipher(
algorithms.AES(key),
modes.CBC(os.urandom(16)), # AES block size = 16 bytes
backend=default_backend()
)
padder = padding.PKCS7(128).padder() # 128 bits = 16 bytes
plain_bytes = padder.update(plain.encode()) + padder.finalize()
encryptor = cipher.encryptor()
ciphertext = encryptor.update(plain_bytes) + encryptor.finalize()
result = cipher.mode.initialization_vector + ciphertext
return binascii.hexlify(result).decode()
Ví dụ sử dụng
if __name__ == "__main__":
KEY = bytes.fromhex(
"6ddf4e7def3233f17984aaaa90e26bfe2859bb349d23d50988661056b6ecc11"
)
encrypted = aes_encrypt(message, KEY)
decrypted = aes_decrypt(encrypted, KEY)
print(f"Original: {message}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
print(f"Match: {message == decrypted}")