python调用aes加解密
时间: 2024-09-28 07:05:03 浏览: 74
在Python中,可以使用第三方库如`cryptography`或`pycryptodome`来实现AES(高级加密标准)的加解密操作。以下是使用`cryptography`库的一个简单示例:
首先,你需要安装`cryptography`库,如果尚未安装,可以在命令行运行:
```bash
pip install cryptography
```
然后你可以这样加解密数据:
**加密**:
```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
# 加密密钥生成
password = b"your_password"
salt = b"your_salt" # 可选,通常从随机源获取
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend())
key = kdf.derive(password)
# AES-GCM模式选择,因为它提供了一定的安全性和完整性检查
cipher = Cipher(algorithms.AES(key), modes.GCM(key), backend=default_backend())
# 实例化一个用于加密的对象
encryptor = cipher.encryptor()
# 假设你有明文数据(data_to_encrypt)
plaintext = b"data_to_encrypt"
# 进行加密
nonce = encryptor.nonce
ciphertext, tag = encryptor.update(plaintext) + encryptor.finalize()
iv = nonce + ciphertext # IV (初始化向量) 和 ciphertext 的组合通常一起存储
阅读全文
相关推荐

















