待加密文本text=‘item_detail:34391311’,key=‘function’,给出CBC模式的AES加密python代码,使用Crypto模块
时间: 2024-10-14 08:12:49 浏览: 37
在Python中,你可以使用`cryptography`库来进行AES加密,包括CBC模式。首先确保已安装该库,如果没有,可以使用`pip install cryptography`命令安装。下面是一个使用CBC模式对给定的待加密文本进行AES-128-CBC加密的示例:
```python
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
def get_key_and_iv(key, salt):
kdf = PBKDF2HMAC(
algorithm=algorithms.HMAC(algorithm=algorithms SHA256()),
length=32,
salt=salt.encode(),
iterations=100000,
backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(key.encode()))
return key.decode(), kdf.derive(16).decode() # IV should be of block size (16 bytes)
def encrypt_CBC(text, key, iv):
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
ct_bytes = encryptor.update(text.encode()) + encryptor.finalize()
return base64.b64encode(ct_bytes).decode()
# 示例用法
salt = b'some_salt'
key, iv = get_key_and_iv('function', salt)
text = 'item_detail:34391311'
encrypted_text = encrypt_CBC(text, key, iv)
print(f"Encrypted text: {encrypted_text}")
阅读全文