实现aes加密解密的代码
时间: 2023-08-01 09:08:19 浏览: 74
以下是一个使用Python实现AES加密和解密的示例代码:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
def encrypt(plain_text, key):
cipher = AES.new(key, AES.MODE_CBC)
cipher_text = cipher.encrypt(pad(plain_text, AES.block_size))
return cipher.iv + cipher_text
def decrypt(cipher_text, key):
iv = cipher_text[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plain_text = unpad(cipher.decrypt(cipher_text[AES.block_size:]), AES.block_size)
return plain_text
# 示例用法
key = get_random_bytes(16) # 生成16字节的随机密钥
plain_text = b'This is a secret message.'
cipher_text = encrypt(plain_text, key)
decrypted_text = decrypt(cipher_text, key)
print("Plain Text:", plain_text)
print("Cipher Text:", cipher_text)
print("Decrypted Text:", decrypted_text)
```
请注意,此示例使用了`pycryptodomex`库,因此您需要先安装该库,可以使用以下命令进行安装:
```
pip install pycryptodomex
```
在示例中,我们使用了AES-CBC模式进行加密和解密。加密函数`encrypt`接受明文和密钥作为输入,并返回包含初始化向量(IV)和密文的字节串。解密函数`decrypt`接受密文和密钥作为输入,并返回解密后的明文。
请注意,在实际使用中,您可能需要对密钥进行更安全的管理,并确保使用适当的填充和模式。此示例仅用于演示目的。