diff --git a/minimal_auth.py b/minimal_auth.py index 04b11ce..84211f6 100644 --- a/minimal_auth.py +++ b/minimal_auth.py @@ -6,30 +6,10 @@ import random import string -def get_credentials(): - username = input('Enter your username: ') - password = str(hashlib.sha256(getpass.getpass('Enter your password: ').encode()).hexdigest()) - return (username, password) - -def authenticate(username, password, pwdb): - return password == pwdb[username] - -def add_user(username, pwdb): - password = getpass.getpass(f'Enter password for {username}: ') - pwdb[username] = str(hashlib.sha256(password.encode()).hexdigest()) - return pwdb - -def read_pwdb(pwdb_path): - try: - pwdb_file = open(pwdb_path, 'rt') - pwdb = json.load(pwdb_file) - except Exception: - pwdb = {} - return pwdb - -def write_pwdb(pwdb, pwdb_path): - pwdb_file = open(pwdb_path, 'wt') - json.dump(pwdb, pwdb_file) +def get_hash(password,salt): + + hash_ = str(hashlib.sha256((password+salt).encode('utf-8')).hexdigest()) + return hash_ def get_salt(char_num=10): """Create random string of characters @@ -44,6 +24,42 @@ def get_salt(char_num=10): return salt +def create_hash(password): + + salt = get_salt(10) + + hash_ = str(hashlib.sha256((password+salt).encode('utf-8')).hexdigest()) + return hash_, salt + +def get_credentials(): + username = input('Enter your username: ') + password = getpass.getpass('Enter your password: ') + + return (username, password) + +def authenticate(username, password, pwdb): + salt = pwdb[username][1] + given_hash = get_hash(password, salt) + return given_hash == pwdb[username][0] + +def add_user(username, pwdb): + password = getpass.getpass(f'Enter password for {username}: ') + hash_, salt = create_hash(password) + pwdb[username] = (hash_, salt) + return pwdb + +def read_pwdb(pwdb_path): + try: + pwdb_file = open(pwdb_path, 'rt') + pwdb = json.load(pwdb_file) + except Exception: + pwdb = {} + return pwdb + +def write_pwdb(pwdb, pwdb_path): + pwdb_file = open(pwdb_path, 'wt') + json.dump(pwdb, pwdb_file) + pwdb_path = 'pwdb.json' pwdb = read_pwdb(pwdb_path)