python用aes加密解密
时间: 2023-10-14 15:06:38 浏览: 46
使用 Python 进行 AES 加密解密可以使用 PyCryptodome 库,它是一个加密学工具包,支持多种加密算法。下面是一个简单的示例:
```python
from Crypto.Cipher import AES
import base64
# 加密函数
def aes_encrypt(key, text):
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
text = text.encode('utf8')
# 为了让长度是16的整数倍,需要进行补全
length = 16
count = len(text)
if count % length != 0:
add = length - (count % length)
else:
add = 0
text = text + (b'\0' * add)
ciphertext = cipher.encrypt(text)
return base64.b64encode(ciphertext).decode('utf8')
# 解密函数
def aes_decrypt(key, text):
cipher = AES.new(key.encode('utf8'), AES.MODE_ECB)
text = base64.b64decode(text.encode('utf8'))
decrypted = cipher.decrypt(text).rstrip(b'\0')
return decrypted.decode('utf8')
# 测试
key = '1234567890123456' # 密钥必须是16、24或32字节长度。
text = 'Hello, AES!'
encrypt_text = aes_encrypt(key, text)
print('加密后的字符串:', encrypt_text)
decrypt_text = aes_decrypt(key, encrypt_text)
print('解密后的字符串:', decrypt_text)
```
注意,AES 加密需要一个 16、24 或 32 字节的密钥,如果密钥长度不足,需要进行补全。在本示例中,我们使用了 ECB 模式,但是这种模式不是很安全,建议使用更加安全的 CBC 模式。此外,加密后的密文需要进行 base64 编码,以便于传输和存储。