def encrypt(data, secret):
"""
Basically wraps the cryptography lib to reduce code duplication
:param data:
:type data: bytes
:param secret:
:type secret: bytes
:return:
:rtype: bytes, str
"""
# Generate a cryptographically secure salt
r = Random.new()
salt = r.read(16)
# Generates a suitable key from the secret by HMACing it with the salt
kdf = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=salt, iterations=100000, backend=default_backend())
key = urlsafe_b64encode(kdf.derive(secret))
# Encrypts the data
f = Fernet(key)
ciphertext = f.encrypt(data)
return b64encode(salt + ciphertext)
评论列表
文章目录