import base64 import os from cryptography.fernet import Fernet from cryptography.hazmat.primitives.kdf.scrypt import Scrypt def fernet_encrypt(value: bytes, key: bytes) -> bytes: f = Fernet(key) token = f.encrypt(value) return token def fernet_decrypt(value, key, return_bytes=False): f = Fernet(key) msg = f.decrypt(value) if return_bytes: return msg return msg.decode("utf-8") def generate_user_passkey(password: str, salt: bytes = None) -> tuple[bytes, bytes]: if salt is None: salt = os.urandom(128) kdf = Scrypt(salt=salt, length=32, n=2**14, r=8, p=1) user_passkey = kdf.derive(password.encode("utf-8")) return salt, base64.b64encode(user_passkey) def generate_random_encryption_key(): return Fernet.generate_key() def serialize_bytes(byte_value): byte_value = base64.b64encode(byte_value) return byte_value.decode("utf-8") def deserialize_into_bytes(string): string = string.encode("utf-8") return base64.b64decode(string)