From b523a7574d015066628ba3f906b7c323bcbc4762 Mon Sep 17 00:00:00 2001 From: StNicolay <103897650+StNicolay@users.noreply.github.com> Date: Mon, 26 Sep 2022 21:15:43 +0300 Subject: [PATCH] Created functions to encrypt and decrypt account info --- src/cryptography/other_accounts.py | 43 ++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/cryptography/other_accounts.py diff --git a/src/cryptography/other_accounts.py b/src/cryptography/other_accounts.py new file mode 100644 index 0000000..f89e12d --- /dev/null +++ b/src/cryptography/other_accounts.py @@ -0,0 +1,43 @@ +import base64 + +import bcrypt + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC +from cryptography.fernet import Fernet + + +def generate_key(salt: bytes, master_pass_hash: bytes) -> bytes: + kdf = PBKDF2HMAC( + algorithm=hashes.SHA256(), + length=32, + salt=salt, + iterations=100000, + backend=default_backend(), + ) + key = base64.urlsafe_b64encode(kdf.derive(master_pass_hash)) + return key + + +def encrypt_account_info( + login: str, passwd: str, master_pass_hash: bytes +) -> tuple[bytes, bytes, bytes]: + """Encrypts login and password of a user using hash of their master password as a key. + Returns a tuple of encrypted login password and salt""" + salt = bcrypt.gensalt() + key = generate_key(salt, master_pass_hash) + f = Fernet(key) + enc_login = f.encrypt(login.encode("utf-8")) + enc_passwd = f.encrypt(passwd.encode("utf-8")) + return (enc_login, enc_passwd, salt) + + +def decrypt_account_info( + enc_login: bytes, enc_pass: bytes, master_pass_hash: bytes, salt: bytes +) -> tuple[str, str]: + key = generate_key(salt, master_pass_hash) + f = Fernet(key) + login_bytes = f.decrypt(enc_login) + pass_bytes = f.decrypt(enc_pass) + return (login_bytes.decode("utf-8"), pass_bytes.decode("utf-8"))