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:

3 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!

2 Likes

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).

3 Likes

Can someone help me understand why this code doesn’t work. I know it has to do with the login() subroutine, but I’ve been fiddling with it for too long and still stuck. The error produced isn’t legible to me. Thanks in advance.

from replit import db
import random

def adduser():
  username = input("Username: ")
  password = input("Password: ")
  salt = random.randint(1,9999)
  newpassword = f"{password}{salt}"
  newpassword = hash(newpassword)
  db[username] = {"password": newpassword, "salt": salt}

def login():
  username = input("Username: ")
  pw = input("Password: ")
  salt = db[username]["salt"]
  newpw = f"{pw}{salt}"
  keys = db.keys() 
  for key in keys: 
    if key in keys:
      if newpw == db["password"]:
        print("Login Successful!")
      else:
        print("Password incorrect")
    else: 
      print("Username incorrect")
  
while True:
  menu = input("1. Add user\n2. Login\n> ")
  if menu == "1":
    adduser()
  else:
    login()
    break
    

What’s that for?
Just check the username’s password.

def login():
  username = input("Username: ")
  if username not in db:
    print('That username does not exist')
    return
  pw = input("Password: ")
  if hash(pw + db[username]["salt"]) == db[username]["password"]:
    print("Login Successful!")
  else:
    print("Password incorrect")
2 Likes

Question: I am not sure why I am getting a key error in my code

Tutorial number: Day 71

Repl link: https://replit.com/@DukeTI/Day71100Days

import random, os, time
from replit import db

def add():
  username = input("Username: ")
  password = input("Password: ")
  salt = random.randint(0000, 9999)
  salt = db[username]["salt"]
  password = password + salt
  password.hash()
  password = db[username]["password"]
  print("\nDetails stored.")

def login():
  username = input("Username: ")
  salt = db[username]["salt"]
  userPass = input("Password: ")
  userPass += salt
  userPass.hash()
  if userPass == db[username]["password"]:
    print(f"\nWelcome {username}")
  else:
    print("\nNope")

while True:
  choice = input("1: Add User, 2: Login >  ")
  if choice == "1":
    add()
  elif choice == "2":
    login()
  time.sleep(2)
  os.system("clear")

:wave: Welcome back @DukeTI!

Well, first of all, you’re using a hash method that doesn’t exist. Instead of doing password.hash(), you should use password = hash(password).

Second of all, you are setting variables to values that don’t exist in the database. That is what is causing the error.
Instead, you should set the database values to the already defined variables.
So instead of this:

salt = db[username]["salt"]
...
password = db[username]["password"]

You should do this:

db[username] = {
    "salt": salt,
    "password": password
}

(After you have defined the salt and hashed password)

Another thing, is you should probably hide the password when getting it from the user.
So import getpass at the top of your file:

from getpass import getpass

And instead of:

password = input("Password: ")

Use this:

password = getpass()
1 Like

I got it. Even though I still don’t understand some of the processes in this lesson that David taught us…I feel he went too fast…

Also am not sure if I did something wrong.

from replit import db
import random
import os, time

def Add():
  Username = input("what's the username?:")
  Password = input("what's the password?:")
  salt = random.randint(1000,9999)
  NewPassword = f"{Password}{salt}"
  NewPassword = hash(NewPassword)
  db[Username] = {"password":NewPassword, "salt":salt}

def Login():
  Username = input("what's the username?:")
  Password = input("what's the password?:")
  salt = db[Username]["salt"]
  NewPassword = f"{Password}{salt}"
  NewPassword = hash(NewPassword)
  
  if NewPassword == db[Username]["password"]:
    print("Login successful!")
  else:
    print("Sorry! Try Again!")


while True:
  print("🌟Login System🌟")
  print()
  menu = input("Add or Login:").strip().capitalize()
  if menu == "Add":
    Add()
  elif menu == "Login":
    Login()
  time.sleep(2)
  os.system("clear")
  print()

is there an error or a problematic symptom?

I’m not sure. Just don’t know if my method of doing it is correct.

Also I feel I literally copied what David taught without understanding (I feel he went a bit fast this lesson)…

2 Likes

What exactly is it that you don’t understand?

2 Likes

I think its how the code really works that (kinda-) OP doesn’t completely understand from the video

1 Like