写个python对称加密的代码,加密函数和解密函数
时间: 2023-04-06 20:00:35 浏览: 186
python实现DES加密解密方法实例详解
5星 · 资源好评率100%
加密函数:
```python
import base64
from Crypto.Cipher import AES
def encrypt(key, plaintext):
# 将明文补齐为16的倍数
plaintext = plaintext + (16 - len(plaintext) % 16) * chr(16 - len(plaintext) % 16)
# 初始化加密器
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# 加密
ciphertext = cipher.encrypt(plaintext.encode('utf-8'))
# 转换为base64编码
return base64.b64encode(ciphertext).decode('utf-8')
```
解密函数:
```python
import base64
from Crypto.Cipher import AES
def decrypt(key, ciphertext):
# 解码base64
ciphertext = base64.b64decode(ciphertext)
# 初始化解密器
cipher = AES.new(key.encode('utf-8'), AES.MODE_ECB)
# 解密
plaintext = cipher.decrypt(ciphertext).decode('utf-8')
# 去掉补齐的字符
plaintext = plaintext[:-ord(plaintext[-1])]
return plaintext
```
其中,key为密钥,plaintext为明文,ciphertext为密文。
阅读全文