python aes加密解密 加上代码注释
时间: 2023-07-10 18:24:49 浏览: 257
好的,以下是加上注释的代码:
```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):
# PBKDF2HMAC算法生成密钥
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(), # 选择hash算法
length=32, # 密钥长度
salt=salt, # 盐值
iterations=100000, # 迭代次数
)
# 生成密钥
key = kdf.derive(password)
return key
# 加密函数
def encrypt(plain_text, password, salt):
# 生成密钥
key = generate_key(password, salt)
# 使用密钥创建Fernet对象
f = Fernet(key)
# 加密明文
cipher_text = f.encrypt(plain_text.encode())
return cipher_text
# 解密函数
def decrypt(cipher_text, password, salt):
# 生成密钥
key = generate_key(password, salt)
# 使用密钥创建Fernet对象
f = Fernet(key)
# 解密密文
plain_text = f.decrypt(cipher_text).decode()
return plain_text
# 示例用法
password = b'password' # 密码,bytes类型
salt = b'salt' # 盐值,bytes类型
plain_text = 'Hello, world!' # 明文,字符串类型
cipher_text = encrypt(plain_text, password, salt) # 加密明文
print(cipher_text)
decrypted_text = decrypt(cipher_text, password, salt) # 解密密文
print(decrypted_text)
```
希望这段代码对你有帮助!
阅读全文