Day 071 - Project 71 : Hashing passwords

Let me walk you through what this larger snippet of code would do, maybe that will help you understand it.

# Import getpass to securely get use's input. Remember we used this for that rock paper
# scissors game?
from getpass import getpass
# Import random to create the salt
from random import randint

# Import the database to create the account
from replit import db

# CREATING AN ACCOUNT

# Get the username. You'd probably want to check if the account already exists, but this
# is just an example
username = input("Username: ")
# Get the password. You can't see what you type, which is why getpass is so useful.
password = getpass()
# Generate a random salt
salt = randint(1000, 9999)
# Hash the password and salt
password = hash(f"{password}{salt}")
# Create the user in the db. You'll understand why we need to store the salt in a second
db[username] = {"password": password, "salt": salt}

# LOGGING IN
# Code is quite similar to creating an account, but is a bit different.

# Get the username
username = input("Username: ")
# Get the password.
password = getpass()
# Now to just check if the user inputted the correct password, but, wait, we don't know what salt
# the user got! How do we figure out what to hash? Oh, yeah, thankfully, we thought ahead and
# already stored the salt.
salt = db[username]["salt"]
# Now we can hash it and check if they entered the right password.
password = hash(f"{password}{salt}")
if password == db["username"]["password"]:
    print("Yay! You entered the right password")
else:
    print("Incorrect password.")
1 Like

Getting this error message for line 34 when running David’s answer:

image

salt = db[username]["salt"]

It seems it doesn’t like one of my usernames as anything else is fine:

image

2 Likes

Hey @MichaelDaburn, that’s because you’re attempting to retrieve the salt value, but it’s not functioning properly. The issue arises because either db[username] or db[username]["salt"] is not structured to support indexing. Could you please share your data structure or the method by which you save the username and its corresponding salt?

Hi, this is David’s (@LessonHacker) answer.

1 Like

I just checked your code out, and I could not replicate this error at all.

Do you mean you checked David’s answer using bigroo and kanga1?

1 Like

No, I tried my own username & password but I will try with bigroo and kanga1.

I’ve created a test repl and it works! For some reason in the tutorial it didn’t want to play ball even though I copied the exact code across in both!

Cheers for being interested :slight_smile:

2 Likes

I see. Yeah, because I couldn’t replicate it even with the given username and password you used. I’m guessing it might be an error in the tutorial.

Maybe but all good now :smiley: Cheers!

1 Like

Just for my own amusement (because I can!) I changed item 3 to ‘delete user’ and kept the ‘delete database’ option as hidden (item 5).

2 Likes