2
\$\begingroup\$

How the program works is that the user sends 2 inputs over (userinput and passwordinput). These are compared against the filename of a textfile (which is the username) and the context (which is the hashed password). The passwordinput gets hashed and if it returns the same as the hashed original password "Access Granted" gets printed. If it doesn't match it prints "Wrong Password!1!!" if the filename doesn't exist it then prints "Username not found." This program is just me playing around with hashlib and trying to find out ways to store passwords on my website, I would like to know more secure ways of writing this code and vulnerabilities

import os
import hashlib

username = "coolcat"
password = "my secret password!!"

result = hashlib.sha256(password.encode("utf-8"))

if not os.path.exists(f"{username}.txt"):
    open(f"{username}.txt", 'w').close()
with open(f"{username}.txt", "w") as file:
   file.write(str(result.digest()))

userinput = input("Your username please : ")
passwordinput = input("Your password please : ")
resulte = hashlib.sha256(passwordinput.encode("utf-8"))
print(str(resulte.digest()))
try :
    with open(f"{userinput}.txt", "r") as file:
        hashed = file.read()
    print(hashed)

    if hashed == str(resulte.digest()):
        print("Access Granted")
    if hashed != str(resulte.digest()):
        print("Wrong password!!")
except FileNotFoundError :
    print("Username not found!!1!")
\$\endgroup\$
3
\$\begingroup\$

WET -vs- DRY

As it stands, your code is very WET (Write Everything Twice). hashlib.sha256(variable.encode("utf-8")) appears twice, and str(variable.digest()) appears four times!

DRY (Don't Repeat Yourself) up your code, by using functions:

def password_hash(password: str) -> str:
    result = hashlib.sha256(password.encode("utf-8"))
    return str(result.digest())

If and if not

Consider these two back-to-back if statements:

    if hashed == str(resulte.digest()):
        print("Access Granted")
    if hashed != str(resulte.digest()):
        print("Wrong password!!")

Assuming resulte.digest() doesn't return different results each time it is called, is there any way to get to both print statements, or neither? No. If you get to the first, you won't get to the second and vise versa. The else clause is used in these cases:

    if hashed == str(resulte.digest()):
        print("Access Granted")
    else:
        print("Wrong password!!")

Pointless code

This code is unnecessary.

if not os.path.exists(f"{username}.txt"):
    open(f"{username}.txt", 'w').close()

If the filename does not exist, it attempts to create an empty file by that name. If it does exist, nothing happens.

The very next statement ...

with open(f"{username}.txt", "w") as file:

... opens the file, whether one existed or not, and writes to it. Creating the file ahead of time was pointless.

Reworked code

import os
import hashlib

def password_hash(password: str) -> str:
    result = hashlib.sha256(password.encode("utf-8"))
    return str(result.digest())

username = "coolcat"
password = "my secret password!!"
hashed_password = password_hash(password)

with open(f"{username}.txt", "w") as file:
   file.write(hashed_password)

userinput = input("Your username please : ")
passwordinput = input("Your password please : ")
hashed_passwordinput = password_hash(passwordinput)
print(hashed_passwordinput)
try:
    with open(f"{userinput}.txt", "r") as file:
        hashed = file.read()
    print(hashed)

    if hashed == hashed_passwordinput:
        print("Access Granted")
    else:
        print("Wrong password!!")
except FileNotFoundError:
    print("Username not found!!1!")

Security

This code will read any .txt file that is accessible to the process. If the user can upload a file /tmp/uploads/myhash.txt, then they can give "/tmp/uploads/myhash" as a "user name", type in the required text that hashes to the given result, and be granted access.

You should sanitize the userinput to ensure it only contains valid username characters.

\$\endgroup\$
1
  • \$\begingroup\$ The security aspect is so clever! \$\endgroup\$ Dec 24 '21 at 11:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.