AES 加解密实例
时间: 2023-08-19 08:05:49 浏览: 47
好的,下面给您提供一个 Python3 中使用 PyCryptodome 库进行 AES 加解密的实例。
首先,需要安装 PyCryptodome 库,可以使用以下命令进行安装:
```
pip3 install pycryptodome
```
然后,可以使用以下代码进行 AES 加解密:
```python
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
# 加密函数
def encrypt(plain_text, key):
cipher = AES.new(key, AES.MODE_CBC)
cipher_text = cipher.encrypt(plain_text)
return cipher.iv + cipher_text
# 解密函数
def decrypt(cipher_text, key):
iv = cipher_text[:16]
cipher = AES.new(key, AES.MODE_CBC, iv)
plain_text = cipher.decrypt(cipher_text[16:])
return plain_text
# 测试
key = get_random_bytes(16) # 随机生成 16 个字节作为密钥
plain_text = b'This is a test message.'
print('原始消息:', plain_text)
cipher_text = encrypt(plain_text, key)
print('加密后的消息:', cipher_text)
decrypt_text = decrypt(cipher_text, key)
print('解密后的消息:', decrypt_text)
```
上述代码中,`encrypt` 函数传入明文和密钥,返回加密后的密文。`decrypt` 函数传入密文和密钥,返回解密后的明文。
在测试中,随机生成了一个 16 字节的密钥,将 `b'This is a test message.'` 进行加密和解密操作,输出结果如下:
```
原始消息: b'This is a test message.'
加密后的消息: b'\x8f\r\x95\xb5\xc3\xe6\x87\xf7\x9c\x9e\xf6\x1c?\xf5\x10\xab\xe9q\x9f\x1a\x9a\x1b\x9d\x8b\xae\x03\x0c\x47\x13\x60\x7a'
解密后的消息: b'This is a test message.'
```
可以看到,经过加密和解密后,原始消息和解密后的消息保持一致,说明加解密操作正确。
需要注意的是,AES 加密算法的安全性非常高,因此在使用时需要注意密钥的安全性,避免密钥泄露。