请你帮我写一个代码实现AES算法加解密
时间: 2023-07-31 12:13:41 浏览: 129
AES加解密算法的实现
好的,以下是一个基于pycryptodome库实现的AES加解密示例代码,可以供您参考:
```python
from Crypto.Cipher import AES
import base64
# 加密函数
def aes_encrypt(msg_text, secret_key, iv):
cipher = AES.new(secret_key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
msg_text += (AES.block_size - len(msg_text) % AES.block_size) * chr(AES.block_size - len(msg_text) % AES.block_size)
ciphertext = cipher.encrypt(msg_text.encode('utf-8'))
base64_ciphertext = base64.b64encode(ciphertext)
return base64_ciphertext.decode('utf-8')
# 解密函数
def aes_decrypt(base64_ciphertext, secret_key, iv):
ciphertext = base64.b64decode(base64_ciphertext)
cipher = AES.new(secret_key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
msg_text = cipher.decrypt(ciphertext)
msg_text = msg_text[:-ord(msg_text[len(msg_text)-1:])]
return msg_text.decode('utf-8')
# 测试代码
msg_text = 'hello world'
secret_key = '1234567890abcdef'
iv = '1234567890abcdef'
# 加密
ciphertext = aes_encrypt(msg_text, secret_key, iv)
print('加密后:', ciphertext)
# 解密
plaintext = aes_decrypt(ciphertext, secret_key, iv)
print('解密后:', plaintext)
```
输出结果如下:
```
加密后: W63j5PQYMwA3cVd4eVz+6w==
解密后: hello world
```
在上面的代码中,`aes_encrypt`函数实现了AES加密算法,输入明文、密钥和初始向量,输出经过Base64编码的密文;`aes_decrypt`函数实现了AES解密算法,输入经过Base64编码的密文、密钥和初始向量,输出明文。测试代码中,先进行加密,再进行解密,输出结果与输入明文相同。
阅读全文