python aes cbc模式加解密
时间: 2023-07-21 16:08:22 浏览: 53
Python中使用AES CBC模式进行加解密可以使用PyCryptodome库。具体步骤如下:
1. 安装PyCryptodome库
可以使用pip命令进行安装:
```
pip install pycryptodome
```
2. 导入库
```
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
```
3. 生成随机密钥和IV
```
key = get_random_bytes(16)
iv = get_random_bytes(16)
```
4. 加密数据
```
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = b'Hello World 1234'
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
```
5. 解密数据
```
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
```
注意事项:
- 密钥长度必须为16、24或32字节。
- IV长度必须为16字节。
- 加密和解密时使用的密钥和IV必须相同。
- 加密前需要对明文进行填充,解密后需要对密文进行去填充。