Python's hashlib produces inconsistent results - python

So I'm trying to write a program that can create an account, by creating a .txt file that's the usernames, and then hashes the password with md5 and puts it in the file. However, whenever I run
hashlib.md5(pasw.encode)
it produces bizarrely inconsistent results, that vary whether it encodes it in a function or not, and last time I tested it seemed to produce a random hash the first time ran. Now, when testing in a new project it sometimes produces the same hash for different strings. I've tried everything I could think of and I've got nothing. You can see some of the things I've tried to do.
Thanks in advance for the help, sorry if my code looks horrible I'm doing this project to learn. Here's the full code, sorry if some is irrelevant:
import hashlib
# Creates an account
def create():
print('Create an account')
user = input('Please enter a username: ')
pasw = input('Please enter a password: ')
usef = user+'.txt'
f = open(usef,'w')
# hash'd it
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
f.write(hash_object)
f.close()
# Logs into a pre-existing account
def login():
print('Welcome! To log in:')
user = input('Please enter a username: ')
pasw = input('Please enter a password: ')
usef = user+'.txt'
# Comparative hash
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
f = open(usef,'r')
# Checks to see if it's right
if hash_object == f:
print('Welcome, '+user+'!')
return(user)
else:
print('User/password not found')
return(0)
# Changes a password for a user
def change(user):
while True:
pasw = input('Please enter your current password: ')
usef = user+'.txt'
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
f = open(usef,'r')
if hash_object == f:
pasw = input('Please enter your new password: ')
past = input('Please repeat your new password: ')
while True:
if pasw == past:
usef = p+'.txt'
f = open(usef,'w')
hash_object = str(hashlib.md5(pasw.encode()))
# Printing hash for debug
print(hash_object)
# This doesn't help but I tried
hash_object = str(hashlib.md5(pasw.encode()))
f.write(hash_object)
f.close()
print('Done!')
return()
else:
print('They aren\'t the same')
pass
else:
print('That doesn\'t match the password on the system')
# Help with commands
def halp():
print('You can type "Create" to create an account')
print('You can type "Login" to log into a pre-existing account')
print('More functionality will be added')
print('Maybe')
# =============== Main Body of Code ==================
while True:
print('What do you want to do?')
print('Type "Help" for commands')
x = input()
x = x.upper()
if x == 'CREATE':
create()
elif x == 'LOGIN':
p = login()
if p != 0:
while True:
print('What would you like to do now?')
print('"Logout" to log out')
print('or "Change password"')
print('I think you can guess that')
x = input()
x = x.upper()
if x == 'CHANGE PASSWORD':
change(p)
elif x == 'HELP':
halp()
elif x == 'DEV':
y = input()
print(str(hashlib.md5(y.encode())))
# This doesn't help but I tried
print(str(hashlib.md5(y.encode())))
else:
print("Command not found")
print("There are four commands")
print("It's not that hard")
edit: Oh, I understand now. Thanks for the help!

Related

why closes my python program without fully executing?

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

Python login limit

i'm trying to implement login attempt system to my current code, but i don't know where i should tick it. Can someone suggest anything? I would like to give three attempts to login, if user fails to login, system will lock user out. I just dont know where to position the code properly.
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
The better way to do this problem is by having a JSON file instead of a txt file. You can have the file in this format:
{
"username": {
"password": "",
"attempts": 0,
}
}
In the login() function increment and write the count of attempts if the password is wrong.
And before the function begins read the JSON and check if the attempts value is greater than 3. If it is greater send an appropriate message else to continue the login action and ask for the password.
Your code had some minor errors which I have handled here:
import re
granted = False
def grant():
global granted
granted = True
def login(name,password):
success = False
file = open("user_details.txt","r")
for i in file:
if i.count(',') > 0: # check whether i has at least one ','
a,b = i.split(",")
b = b.strip()
if(a==name and b==password):
success=True
break
file.close()
if(success):
print("Login Succesful")
grant()
else:
print("wrong username or password")
def register(name,password):
file = open("user_details.txt","a")
file.write( "\n"+name[0]+","+password) # name is an array so only the first element is stored.
file.close()
grant()
def access(option):
global name
if(option=="login"):
name = input("Enter your name: ")
password = input("enter your password: ")
login(name,password)
else:
print("Enter yor name and password to register")
name = input("Please enter your name: ").lower().split()
if len(name) > 1:
first_letter = name[0][0]
three_letters_surname = name[-1][:3].rjust(3, 'x')
name = '{}{}'.format(first_letter, three_letters_surname)
print(name)
while True:
password = input("Enter a password: ")
if len(password) < 8:
print("Make sure your password is at lest 8 letters")
elif re.search('[0-9]',password) is None:
print("Make sure your password has a number in it")
elif re.search('[A-Z]',password) is None:
print("Make sure your password has a capital letter in it")
else:
print("Your password seems fine")
break
register (name,password)
def begin():
global option
print("Welcome to Main Menu")
option = input("Login or Register (login,reg): ")
if(option!="login" and option!="reg"):
begin()
begin()
access(option)
if(granted):
print("Welcome to main hub")
print("#### Details ###")
print("Username:",name)

ValueError: I/O operation on closed file inside an if statement

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!")

Password - Login not working Python

I just finished Coursera's Python for Everybody 1st course.
To practice my skills, I decided to make a password and username login. Whenever I create a username, I get my user set error which says 'Invalid credentials'. Here is my code.
import time
import datetime
print ('storingData')
print("Current date and time: ", datetime.datetime.now())
while True:
usernames = ['Admin']
passwords = ['Admin']
username = input ('Please enter your username, to create one, type in create: ')
if username == 'create':
newname = input('Enter your chosen username: ')
usernames.append(newname)
newpassword = input('Please the password you would like to use: ' )
passwords.append(newpassword)
print ('Temporary account created')
continue
elif username in usernames :
dataNum = usernames.index (username)
cpasscode = passwords[dataNum]
else:
print ('Wrong credentials, please try again')
continue
password = input ('Please enter your password: ')
if password == cpasscode:
print ('Welcome ', username)
The code as it appears in my editor
In your code, you have initialized your usernames array right after the while statement. This means that every time it loops back to the beginning, it re-initializes, losing anything that your previously appended. If you move the array initialization outside of the loop, it should work as expected.
This works for python 3. for python 2 you must take input differently refer: Python 2.7 getting user input and manipulating as string without quotations
import time
import datetime
names = ['Admin']
pwds = ['Admin']
while True:
name = input('Name/create: ')
if name == "create":
name = input('New Name: ')
pwd = input('New Pwd : ')
names.append(name)
pwds.append(pwd)
continue
elif name in names:
curpwdindex = names.index(name)
print(names)
curpwd = pwds[curpwdindex]
givenpwd = input('Password: ')
if givenpwd == curpwd:
print("Welcome")
break
else:
print("Inavlid Credential")
else:
print("Wrong Choice")
continue

How to store multiple items in one pickle dictionary?

I am currently attempting to make a login/signup program on my computer that will allow for multiple sets of usernames and passwords. Right now anytime I sign up, it overwrites the previous login. I am using Python 3.4.
Is there a way I can prevent this?
My code is available below:
import os
import pickle
import sys
import time
user_name = 'default'
pass_word = '12345'
login = {'username' : user_name,
'password' : pass_word}
def cls():
os.system('cls')
def space():
print(' ')
def load():
with open('logins', 'rb') as f:
login = pickle.load(f)
def save():
with open('logins', 'wb') as f:
pickle.dump(login, f)
def MainMenu():
print('Select an Option.')
while True:
print('1) Login')
print('2) Signup')
user_input = input('Option #: ')
if user_input == '1':
cls()
login_user()
elif user_input == '2':
cls()
signup_user()
else:
cls()
continue
def signup_user():
user_chosen_name = input('Username: ')
login['username'] = user_chosen_name
user_chosen_password = input('Password: ')
login['password'] = user_chosen_password
space()
cls()
print('Setup complete. Please login.')
os.system('pause')
save()
cls()
login_user()
def login_user():
load()
while True:
print('Please Login.')
space()
user_input_name = input('Username: ')
user_input_password = input('Password: ')
if user_input_name == login['username'] and user_input_password == login['password']:
space()
print('Login Successful.')
else:
space()
print('Login Failed. Please Try Again.')
while True:
print('1) Try Again.')
print('2) Main Menu.')
user_cont = input('Continue?: ')
if user_cont == '1':
cls()
break
elif user_cont == '2':
cls()
MainMenu()
break
if __name__ == '__main__':
if os.path.isfile('logins') == False:
save()
else:
pass
MainMenu()
Here are two proposals for the login/password data model.
Use a dictionary, this is probably the simplest way ; I suggest using this.
# init with default
passwords = {user_name: pass_word}
# password look-up
if login in passwords:
print passwords[login]
else:
print 'User', login, 'is not registered'
# password set or update
password[login] = new_password
List of couples or list of dictionaries.
This may be closer to your current solution, but I would not recommend it.
I only show what the initialization would be.
# list of couples
logins = [(user_name, pass_word)]
# list of dictionaries
logins = [{'username' : user_name,
'password' : pass_word}]

Categories

Resources