帮我写一个加解密AES的python程序
时间: 2023-05-22 10:06:29 浏览: 60
当然,我很乐意帮您写一个AES加解密的Python程序。以下是基于pycrypto库实现的AES加解密程序示例:
```python
from Crypto.Cipher import AES
import base64
key = 'This is a key123'
iv = 'This is an IV456'
# 加密函数
def encrypt(text):
aes = AES.new(key, AES.MODE_CBC, iv)
# 注意:由于加密结果中可能包含特殊字符,必须进行base64编码
ciphertext = base64.b64encode(aes.encrypt(text))
return ciphertext
# 解密函数
def decrypt(ciphertext):
aes = AES.new(key, AES.MODE_CBC, iv)
# 注意:对加密结果进行base64解码
text = aes.decrypt(base64.b64decode(ciphertext)).rstrip(b'\0')
return text
# 测试
text = 'Hello, world!'
print('原始文本:', text)
ciphertext = encrypt(text)
print('加密结果:', ciphertext)
decrypted_text = decrypt(ciphertext)
print('解密结果:', decrypted_text.decode('utf-8'))
```
需要注意的是,由于加密结果中可能包含特殊字符,因此加密时需要进行base64编码,解密时需要先对加密结果进行base64解码。
另外需要说明的是,本程序中使用的是AES模式中的CBC模式,使用时需要注意选择合适的加密模式。