I have a login program that hashes a string and stores it in a file to create a new account. When I need to log in, the login detail strings get hashed, and the program checks if the hashed strings have a match in the file. The program works without hashing, but when I hash the identical login details, the hash values are not the same. I have checked and the strings are exactly the same. Here is my code:
import tkinter
import math
import os
import hashlib
# The login function #
def login(username, password, file_path):
file_new = open(file_path, "a")
file_new.close()
file = open(file_path, "r")
file_content = file.read()
print(file_content)
file.close()
hashed_username = hashlib.md5(bytes(username, "utf-8"))
hashed_password = hashlib.md5(bytes(password, "utf-8"))
print(f"Hashed username: {hashed_username}, hashed password: {hashed_password}")
if f"{hashed_username},{hashed_password}" in file_content[:]:
return "You were logged in successfully"
else:
return "We could not find your account. Please check your spelling and try again."
# The account creation function #
def newaccount(username, password, file_path):
file_new = open(file_path, "a")
file_new.close()
# Reading the file #
file = open(file_path, "r")
file_content = file.read()
print(file_content)
file.close()
# Hashing the account details #
hashed_username = hashlib.md5(bytes(username, "utf-8"))
hashed_password = hashlib.md5(bytes(password, "utf-8"))
print(f"Hashed username: {hashed_username}, hashed password: {hashed_password}")
file_append = open(file_path, "a")
# Checking to see if the details exist in the file #
if f"{hashed_username},{hashed_password}" in file_content[:]:
file_append.close()
return "You already have an account, and were logged in successfully"
else:
# Writing the hashed details to the file #
file_append.write(f"{hashed_username},{hashed_password}\n")
file_append.close()
return "New account created."
logins_path = "Random Scripts\Login Program\logins.txt"
signin_message = input("Would you like to: \n1. Create an account \nor \n2. Log in\n")
if signin_message == "1":
print("User chose to create account")
newacc_username = input("Input a username: ")
newacc_password = input("Input a password: ")
print(newaccount(newacc_username, newacc_password, logins_path))
elif signin_message == "2":
print("User chose to log in")
username = input("Input your username: ")
password = input("Input your password: ")
print(login(username, password,logins_path))
else:
print("Please enter 1 or 2")
hashed_username = hashlib.md5(bytes(username, "utf-8"))
This function returns a hash object, and when you print it or write it to a file, you get something like this:
<md5 HASH object # 0x7f8274221990>
... which isn't terribly useful.
If you want the actual text of the hashes, call .hexdigest():
hashed_username = hashlib.md5(bytes(username, "utf-8")).hexdigest()
# returns e.g. "47bce5c74f589f4867dbd57e9ca9f808"
Related
loginUsername = input("Enter Username: ")
loginPassword = input("Enter PASSWORD: ")
data=open('database.txt', 'r')
accounts = data.readlines()
for line in data:
accounts = line.split(",")
if (loginUsername == accounts[0] and loginPassword == accounts[1]):
print("LOGGED IN")
else:
print("Login FAILED")
print(accounts)
I want to make a text login system, which will ask for the username first. After checking the text file which stored username and password, the system will ask for password. But I don't know how to read the first column (which is username, the structure of the text file is "username, password"). If i use readlines() and split(","). But there is "n" at the end of the password.
# You should always use CamelCase for class names and snake_case
# for everything else in Python as recommended in PEP8.
username = input("Enter Username: ")
password = input("Enter Password: ")
# You can use a list to store the database's credentials.
credentials = []
# You can use context manager that will automatically
# close the file for you, when you are done with it.
with open("database.txt") as data:
for line in data:
line = line.strip("\n")
credentials.append(line.split(","))
authorized = False
for credential in credentials:
db_username = credential[0]
db_password = credential[1]
if username == db_username and password == db_password:
authorized = True
if authorized:
print("Login Succeeded.")
else:
print("Login Failed.")
The "n" at the end of the password is probably the newline character \n. In order to remove it, you can use the rstrip() function:
mystring = "password\n"
print(mystring.rstrip())
>>> 'password'
I am completely new to programming and started a few days ago with learning Python(v.3.8.8). I wanted to make a small password manager, but with a little secret function(I think that's not important and it would take too much time to describe). Anyways I converted the main.py to a .exe with auto-py-to-exe but every time I wanna execute the .exe I can only enter my Login data and the window instantly closes but in Pycharm everything works totally fine. Does anyone know why?
EDIT: It works now, there was no missing "Input()" or stuff like that, I had a spelling mistake in my code and pycharm ignored it!
from cryptography.fernet import Fernet
welcome = input("Login(1), New User (2): ")
def new_user(): # creates a new user and safe the Username and pw in a .txt
print("The login is just for the safety of your data, everything is stored on your local PC!")
username = input("Enter a username:")
password = input("Enter a password:")
password1 = input("Confirm password:")
if password == password1:
key = Fernet.generate_key()
f = Fernet(key)
f.encypt(b'password')
file = open(username + ".txt", "w")
file.write(username + ":" + password)
#file.close()
login() # go to login after everything is safed in the .txt
else:
print("Passwords do NOT match!")
def login(): # checks if the entered username and pw match with the .txt content
login1 = input("Login:")
login2 = input("Password:")
file = open(login1 + ".txt", "r")
pw = file.readline()
#file.close()
if pw == login1 + ":" + login2: # infinte trys to enter the username and pw
print("Welcome " + login1)
pwrequest()
else: # returns to login() if the pw is incorrect
print("Incorrect username or password. Please try again")
login()
def pwrequest():
q = input("safe new Password(1), show safed passwords(2)")
if q == "2":
data() # show all saved pw
if q == "1":
newdata() # go to data() if the user want to add a new pw or
# want to acces the hidden part
def data():
file = open('1.txt', 'r') # prints all saved passwords
file_pw = file.read()
print(file_pw)
file.close()
c = input("Press (1) to delete something and press (2) to log out.")
if c == '1':
delete() # delete a pw or acces to hidden part
if c == '2':
login() # simple logout system, probably have to change this to something more intermediate
def newdata(): # safes the data in variables and put it in a .txt file
company = input("Enter the companys name: ")
username = input("Enter your username: ")
password = input("Enter your password: ")
print(company + username + password + ", is everything correct?")
a = input("y/n")
if a == "y":
file = open("1.txt", "w")
file.write(
"Company: " + company + "\n" + "Username: " + username + "\n" + "Password: " + password + "\n" + "\n")
file.close()
pwrequest() # return to pwrequest()
if a == "n":
newdata() # return to newdata() if something is incorrect
secretWord = "CompanyUsernamePassword" # define the secret word to finaly acces the hidden part
if company + username + password == secretWord:
secrettest() # go to secrettest() to enter the secret word
def delete(): # just simple code that delete specific content of the pw .txt
name = input("Please enter the Company, Username and password you wanna delete: ")
with open("1.txt", "r") as f:
lines = f.readlines()
with open("1.txt", "w") as f:
for line in lines:
if line.strip("\n") != name:
f.write(line)
def secrettest():
key = Fernet.generate_key()
f = Fernet(key)
truepass = f.encrypt(b"Test1234")
trys = 3
while trys != 0: # checks if you entered the correct pw and if not count 2 times
password = input("Pls enter the password: ")
d = f.decrypt(truepass)
if password == d.decode():
print(truepass)
break
else:
print("Wrong password!")
trys -= 1
if trys == 0:
print("You entered the wrong password to many times!")
if welcome == "1": # should probably try to move that to the top
login()
if welcome == "2": # this too
new_user()
I think I know why the .exe always closes. I executed the .exe in the windows cmd, and got this error "AttributeError: 'Fernet' object has no attribute 'enrcypt'". I'm kinda sure that this is the part that caused the trouble. I'm just wondering why pycharm just ignored this error...
I made a login/signup program where the user must type in credentials in order to make an account or enter.
But I have two problems though, one is inside the function 'sign_up()' if the user is attempting to make a pre-existing account it should print the 'This username is taken' statement, but that's not the case. It prints a Value Error called 'I/O operation on closed file' instead.
Then the second problem is, it doesn't print the credentials in a designated file called 'LOG-IN_DATA', it's basically where you store it.
Anyway here is the code:
from class1 import Credentials
def sign_up():
choose_username_data = input("Choose a UserName: ")
choose_password_data = input("Choose your password: ")
Credentials(choose_username_data, choose_password_data)
data = open('LOG-IN_DATA', 'a+')
if choose_username_data not in data:
data.write(str(Credentials))
data.write('\n')
welcome()
data.close()
if choose_username_data in data:
print("This username is taken!")
sign_up()
data.close()
def log_in():
username_data = input("Enter your username: ")
password_data = input("Enter your password: ")
data = open('LOG-IN_DATA', 'r')
data.read()
data.close()
if username_data and password_data in data:
welcome()
elif username_data and password_data not in data:
print("Username or Password does not match or not recognized.")
log_in()
def welcome():
print("Welcome! You made it in!")
def login_or_signup():
signup_var = ('Signup', 'SignUp', 'signup')
login_var = ('Login', 'LogIn', 'login')
prompt_user = input("Welcome! Would you like to Login or Signup?: ")
if prompt_user in login_var:
log_in()
elif prompt_user in signup_var:
sign_up()
else:
print("\nChoose 'Login' or 'Signup'")
login_or_signup()
login_or_signup()
Sorry if the code is too long. I just want problems and potential ones to be eliminated as far as I am concerned.
Anyways thank you in advance!
Try using with statements when manipulating files. It handles flush and close automatically even when errors occur.
For example:
with open("path", 'r') as f:
content = f.read()
instead of:
f = open("path", 'r')
content = f.read()
f.close()
The problem with this line if choose_username_data in data: is that before, you also used data. The cursor in the file is at the end of this file. So when you ask a second time without setting the cursor back to the start of the file, it read nothing. That's why the 2nd statement never evaluates true.
With everything I told you, the sign_up function can be written:
def sign_up():
loop = True
while loop:
choose_username_data = input("Choose a username: ")
choose_password_data = input("Choose your password: ")
creds = Credentials(choose_username_data, choose_password_data)
with open('LOG-IN_DATA', 'a+') as data:
content = data.read()
if choose_username_data not in content:
data.write(str(creds)+'\n')
welcome()
loop = False
# if choose_username_data in content:
else:
print("This username is taken!")
I am learning python. I wanted to learn to work with text files, so I decided to make a simple console program.
The program does the following:
Asks if you had already a profile.
If no, then asks to create a username and a password. The information is saved in a text file.
If yes, then asks to input your password and username.
When the user doesn't have a profile, everything works well. When the user has a profile and wants to log in, it doesn't work and I don't know why.
The username is saved in the first line of the text file and the password in the second line, so, I use readlines()[0] and readlines()[1].
The username is recognized correctly, but the password doesn't. I get this error
Traceback (most recent call last):
File "Archivo de prueba.py", line 4, in <module>
print(text_file.readlines()[1])
IndexError: list index out of range
This is the code I wrote:
text_file = open("Archivo de prueba.txt", "r+")
def ask_for_account():
global has_account
has_account = input("Do you have an account? (Write \"Yes\" or \"No) ")
ask_for_account()
def create_profile():
create_user = str(input("Type your new username: "))
create_password = str(input("Type your new password: "))
text_file.write(create_user)
text_file.write("\n")
text_file.write(create_password)
def login():
username = text_file.readlines()[0]
password = text_file.readlines()[1]
current_user = input("Type your username: ")
current_password = input("Type your password: ")
if str(current_user) == str(username) and str(current_password) == str(password):
print("Succesfully logged in.")
else:
print("Invalid username or password")
if has_account == "No":
create_profile()
elif has_account == "Yes":
login()
else:
print("Invalid input")
ask_for_account()
text_file.close()
The following code works. I added a few comments to indicate changes.
def ask_for_account():
return input("Do you have an account? (Enter 'Yes' or 'No') ")
def create_profile():
create_user = str(input("Type your new username: "))
create_password = str(input("Type your new password: "))
# Open the file for writing and close it after use.
text_file = open("Archivo de prueba.txt", "w")
text_file.write("{}\n".format(create_user))
text_file.write("{}\n".format(create_password))
text_file.close()
def login():
# Open the file for reading and close it after use.
text_file = open("Archivo de prueba.txt", "r")
lines = text_file.readlines()
text_file.close()
# remove the newline at the end of the input lines.
username = lines[0].rstrip()
password = lines[1].rstrip()
current_user = input("Type your username: ")
current_password = input("Type your password: ")
if current_user == username and current_password == password:
print("Succesfully logged in.")
else:
print("Invalid username or password")
#
# Put program logic in one place after the methods are defined.
#
has_account = ask_for_account()
if has_account == "No":
create_profile()
elif has_account == "Yes":
login()
else:
print("Invalid input")
username = text_file.readlines()[0]
password = text_file.readlines()[1]
The first call to readlines() consumes the entire file and there are no lines remaining for the second call to read, so it returns an empty list.
Read the file once and save the lines in a list, then pick the desired lines from the list:
file_lines = text_file.readlines()
username = file_lines[0]
password = file_lines[1]
Also, be aware that readlines() puts a carriage return \n at the end of every line, so you might have to strip that off depending on how you use these values.
I learned about creating files using python in computer science at school. I have created a piece of code where you can create a username and password and then it saves to a csv file. There is also another option where you can log in. It asks you to enter the username and if it is wrong it says "Username not found". Whatever I enter (even though it is correct) it says Username not found.
This is the main part of the code:
Log = input("Enter Choice here: ")
if Log == "Log In" or Log == "log in" or Log == "Log in" or Log == "log In":
Data = open("F:\\'Filename'.csv", "r")
SavedUser = Data.readline()
Username = input("Username: ")
if Username == SavedUser:
print("Welcome", Username, "!")
Password = input("Password: ")
if Password == Data.readline():
print("It works")
Thank you for all your help.
Your CSV file is probably not being read correctly. Python has a csv library to parse CSV files correctly. What you can do is read the CSV file to a dictionary and then compare username and password.
import csv
action = input("Enter Choice here: ")
if action.lower() == "Log In".lower(): #Convert both strings two lowercase and then compare
reader = csv.reader(open('demo.csv', 'r')) #parsing the csv file correctly
user_dict = dict(reader) #converting iterable reader directly to a dictionary
#{'abc': 'abc123', 'username': 'password'}
username_input = input("Username:")
if username_input in user_dict: #check if username exists as a key in the dictionary
print("Welcome", username_input, "!")
password_input = input("Password: ")
if password_input == user_dict[username_input]:
print("It works")