python实现AES算法CBC模式加解密
时间: 2023-07-31 18:13:42 浏览: 68
好的,以下是Python实现AES算法CBC模式加解密的代码:
```python
from Crypto.Cipher import AES
import base64
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[:-ord(s[len(s)-1:])]
class AESCipher:
def __init__(self, key):
self.key = key.encode('utf-8')
def encrypt(self, raw):
raw = pad(raw).encode('utf-8')
iv = b'0000000000000000'
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(cipher.encrypt(raw)).decode('utf-8')
def decrypt(self, enc):
enc = base64.b64decode(enc.encode('utf-8'))
iv = b'0000000000000000'
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return unpad(cipher.decrypt(enc)).decode('utf-8')
```
使用方法示例:
```python
key = '1234567890123456'
cipher = AESCipher(key)
# 加密
encrypted = cipher.encrypt('hello world')
print(encrypted)
# 解密
decrypted = cipher.decrypt(encrypted)
print(decrypted)
```
注意事项:
1. key的长度必须为16、24、32位,分别对应AES-128、AES-192、AES-256加密算法。
2. 由于CBC模式需要一个初始向量IV,这里默认使用16个0。实际使用中,IV应该是随机的,并且需要和密文一起传输。