This repository has been archived on 2023-08-08. You can view files and clone it, but cannot push or open issues or pull requests.
PassManager/src/encryption/master_pass.py

43 lines
1023 B
Python

import os
from cryptography.exceptions import InvalidKey
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from ..db.models import MasterPass
MEMORY_USAGE = 2**14
def _get_kdf(salt: bytes) -> Scrypt:
kdf = Scrypt(
salt=salt,
length=128,
n=MEMORY_USAGE,
r=8,
p=1,
)
return kdf
def encrypt_master_pass(user_id: int, password: str) -> MasterPass:
"""Hashes master password and returns MasterPass object"""
salt = os.urandom(64)
kdf = _get_kdf(salt)
password_hash = kdf.derive(password.encode("utf-8"))
return MasterPass(
user_id=user_id,
password_hash=password_hash,
salt=salt,
)
def check_master_pass(password: str, master_password: MasterPass) -> bool:
"""Checks if the master password is correct"""
kdf = _get_kdf(master_password.salt)
try:
kdf.verify(password.encode("utf-8"), master_password.password_hash)
except InvalidKey:
return False
else:
return True