给出一段CBC的分组加密模式的代码
时间: 2023-12-14 08:39:16 浏览: 16
以下是一个使用CBC模式的AES分组加密代码示例,使用Python的pycryptodome库:
```python
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
# 初始化加密器
key = b'0123456789abcdef'
iv = b'fedcba9876543210'
cipher = AES.new(key, AES.MODE_CBC, iv)
# 加密明文
plain_text = b'This is a secret message.'
padded_plain_text = pad(plain_text, AES.block_size)
cipher_text = cipher.encrypt(padded_plain_text)
# 解密密文
decipher = AES.new(key, AES.MODE_CBC, iv)
decrypted_text = decipher.decrypt(cipher_text)
unpadded_decrypted_text = unpad(decrypted_text, AES.block_size)
print('Plain text: ', plain_text)
print('Cipher text: ', cipher_text)
print('Decrypted text: ', unpadded_decrypted_text)
```
在上述代码中,使用了CBC模式进行AES加密。其中,key为密钥,iv为初始化向量,cipher为加密器对象。明文通过pad函数进行填充,并使用encrypt方法进行加密;密文通过decrypt方法进行解密,并使用unpad函数进行去填充。