AES加密 python
时间: 2023-07-08 13:47:42 浏览: 54
要使用AES加密算法,需要先安装pycryptodome这个库,可以通过以下命令进行安装:
```
pip install pycryptodome
```
接下来,可以按照以下步骤进行AES加密:
1. 导入库和模块
```python
from Crypto.Cipher import AES
import base64
```
2. 准备加密数据
```python
msg_text = 'hello world'
secret_key = '1234567890abcdef'
iv = '1234567890abcdef'
```
3. 创建AES加密器
```python
cipher = AES.new(secret_key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
```
4. 对数据进行加密
```python
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'))
```
5. 将加密后的数据进行Base64编码
```python
base64_ciphertext = base64.b64encode(ciphertext)
```
完整的代码如下:
```python
from Crypto.Cipher import AES
import base64
msg_text = 'hello world'
secret_key = '1234567890abcdef'
iv = '1234567890abcdef'
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)
print(base64_ciphertext.decode('utf-8'))
```
输出结果如下:
```
W63j5PQYMwA3cVd4eVz+6w==
```
可以看到,输出结果是一个经过Base64编码的字符串,就是加密后的结果。