调用Python库,实现aes128的加密和解密
时间: 2024-03-05 21:54:41 浏览: 15
好的,可以使用Python中的`pycryptodome`库实现AES-128加解密。
首先,需要安装`pycryptodome`库,可以使用以下命令进行安装:
```
pip install pycryptodome
```
接下来,我们可以定义一个函数,用于实现AES-128的加密和解密。具体实现代码如下:
```python
from Crypto.Cipher import AES
import base64
def aes_encrypt(key, data):
"""
AES-128加密函数
:param key: 密钥,必须为16、24、32字节中的一个
:param data: 需要加密的数据,必须为16字节的整数倍
:return: 加密后的数据(base64编码)
"""
cipher = AES.new(key, AES.MODE_ECB)
encrypted_data = cipher.encrypt(data)
return base64.b64encode(encrypted_data).decode('utf-8')
def aes_decrypt(key, encrypted_data):
"""
AES-128解密函数
:param key: 密钥,必须为16、24、32字节中的一个
:param encrypted_data: 需要解密的数据(base64编码)
:return: 解密后的数据
"""
cipher = AES.new(key, AES.MODE_ECB)
decrypted_data = base64.b64decode(encrypted_data)
return cipher.decrypt(decrypted_data).decode('utf-8')
```
其中,`key`参数为密钥,必须为16、24、32字节中的一个;`data`参数为需要加密的数据,必须为16字节的整数倍;`encrypted_data`参数为需要解密的数据,必须为加密后的数据进行base64编码后的结果。
下面是一个使用示例:
```python
key = b'this is a 16 key' # 密钥必须为16字节
data = b'test data test data' # 需要加密的数据必须为16字节的整数倍
# 加密
encrypted_data = aes_encrypt(key, data)
print('加密后的数据:', encrypted_data)
# 解密
decrypted_data = aes_decrypt(key, encrypted_data)
print('解密后的数据:', decrypted_data)
```
输出结果:
```
加密后的数据: IxQjG2aBC3L7Xg69bI0vLQ==
解密后的数据: test data test data
```
希望能够帮到你!