python aes加密解密
时间: 2023-06-22 10:29:01 浏览: 108
python实现AES加密解密
可以使用 Python 的 cryptography 模块实现 AES 加密解密。以下是示例代码:
```python
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
def generate_key(password, salt):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
)
key = kdf.derive(password)
return key
def encrypt(plain_text, password, salt):
key = generate_key(password, salt)
f = Fernet(key)
cipher_text = f.encrypt(plain_text.encode())
return cipher_text
def decrypt(cipher_text, password, salt):
key = generate_key(password, salt)
f = Fernet(key)
plain_text = f.decrypt(cipher_text).decode()
return plain_text
```
其中,generate_key 函数通过 PBKDF2HMAC 算法生成密钥,encrypt 函数使用生成的密钥加密明文,decrypt 函数使用密钥解密密文。password 和 salt 参数分别为密码和盐值,可以随机生成并保存在安全的地方。注意,加密后的密文需要进行安全传输或存储。
示例用法:
```python
password = b'password'
salt = b'salt'
plain_text = 'Hello, world!'
cipher_text = encrypt(plain_text, password, salt)
print(cipher_text)
decrypted_text = decrypt(cipher_text, password, salt)
print(decrypted_text)
```
阅读全文