add password hashing #8

Open
jiamengwu wants to merge 2 commits from jiamengwu/2025-plovdiv-git:hashing into live_coding

View file

@ -1,17 +1,27 @@
import getpass # hides types characters, very useful import getpass # hides types characters, very useful
import json import json
import sys import sys
import hashlib # python standard lib for hashing
def get_credentials(): def get_credentials():
username = input('Enter your username: ') username = input('Enter your username: ')
password = getpass.getpass('Enter your password: ') password = getpass.getpass('Enter your password: ')
return (username, password) return (username, password)
# add a function that hashes the password
def hash_password(password):
return hashlib.sha256(f'{password}'.encode()).hexdigest()
def authenticate(username, password, pwdb): def authenticate(username, password, pwdb):
return password == pwdb[username] correct_password = pwdb[username]
# add this line to hash the entered password to then compared with the stored password
attempted_password = hash_password(password)
return correct_password == attempted_password
def add_user(username, pwdb): def add_user(username, pwdb):
pwdb[username] = getpass.getpass(f'Enter password for {username}: ') password = getpass.getpass(f'Enter password for {username}: ')
# hash the password before saving to the database
pwdb[username] = hash_password(password)
return pwdb return pwdb
def read_pwdb(pwdb_path): def read_pwdb(pwdb_path):