From 75984d1f1f2b92a80fb84fb8d647b442d149cbac Mon Sep 17 00:00:00 2001 From: HeshamTB Date: Wed, 16 Mar 2022 22:30:57 +0300 Subject: [PATCH] sql_app: crypto: added crypto python helper fucntions Idea is to isolate cryptography from database managment code. Signed-off-by: HeshamTB --- sql_app/crypto.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 sql_app/crypto.py diff --git a/sql_app/crypto.py b/sql_app/crypto.py new file mode 100644 index 0000000..1f4a018 --- /dev/null +++ b/sql_app/crypto.py @@ -0,0 +1,29 @@ + +import os +from hashlib import pbkdf2_hmac + +PASS_ENCODING='utf-8' +HASH_FUNC='sha256' +NUM_ITIRATIONS=100000 + +def get_new_salt(n_bytes : int = 32) -> bytes: + + if type(n_bytes) != int: + n_bytes = 32 # Forece in case of misuse + + return os.urandom(n_bytes) + +""" +Generate a new key and salt to store. +Returns (key, salt) +""" +def gen_new_key(plain_passwd : str) -> tuple: + salt = get_new_salt(32) + return (calc_key(plain_passwd, salt), salt) + +def verify_key(plain_passwd : str, salt : bytes, stored_key : bytes) -> bool: + key_tmp = calc_key(plain_passwd, salt) + return (stored_key == key_tmp) + +def calc_key(passwd: str, salt : bytes) -> bytes: + return pbkdf2_hmac(HASH_FUNC, passwd.encode(PASS_ENCODING), salt, NUM_ITIRATIONS) \ No newline at end of file