aes加密python实现
时间: 2024-11-22 12:28:28 浏览: 7
AES (Advanced Encryption Standard) 是一种常用的对称加密算法,Python 中可以使用 `cryptography` 库来轻松实现 AES 加密。以下是简单的步骤:
```python
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
# 导入密钥、初始化向量(IV)
key = b'your_secret_key_32_bytes' # 通常32字节(256位)
iv = b'your_initialization_vector_16_bytes' # 通常16字节
def encrypt(plaintext):
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
padder = padding.PKCS7(cipher.block_size).padder()
padded_plaintext = padder.update(plaintext) + padder.finalize()
ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
return ciphertext
def decrypt(ciphertext):
backend = default_backend()
decipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend).decryptor()
unpadder = padding.PKCS7(cipher.block_size).unpadder()
decrypted_ciphertext = decipher.update(ciphertext) + decipher.finalize()
plaintext = unpadder.update(decrypted_ciphertext) + unpadder.finalize()
return plaintext.decode('utf-8') # 如果你的数据是字符串
# 示例
plaintext = "Hello, world!"
ciphertext = encrypt(plaintext.encode('utf-8'))
decrypted_text = decrypt(ciphertext)
print(f"原始文本: {plaintext}")
print(f"加密后的文本: {ciphertext.hex()}")
print(f"解密后的文本: {decrypted_text}")
```
阅读全文