I am doing a fun little project, making a kind of secret code program with a GUI(Tkinter) to encrypt my text(not very securely). I am trying to make a password on this program linked to a txt file. The program has default password 'abc', stored in a text file in sha-224. When the user enters 'abc', it will hash their input in sha-224, and compare it to the stored password in _hexutf2.txt. Once they have logged in, the user will have the option to choose a new password by clicking New Passcode, entering their previous passcode, clicking next, and then clicking new code. After clicking new code, the user enters a new passcode in the entrypassVariable, then clicks enter passcode, which will write the new passcode on the txt file. Instead, the program hangs on the first pressing of Enter passcode, despite the fact that I had entered 'abc' the default passcode. The program worked before I added the password element, so I will post only the password code here, but I will link to the entire program if anyone wants to see it.
EDIT
Posting just the essential code here. The problem in my main program is caused by this. For some reason, this program prints this:
Stored Password: cd62248424c8057fea8fff161ec753d7a29f47a7d0af2036a2e79632
Enter Password: Moo
Password Attempt Hash: cd62248424c8057fea8fff161ec753d7a29f47a7d0af2036a2e79632
Password Incorrect
http://snipplr.com/view/75865/cryptographer/ <----Entire program code
import hashlib
passfile = open('pass.txt','r')
stored_password = str(passfile.read())
print 'Stored Password: ' + stored_password
password = raw_input('Enter Password: ')
enter_pass_sha = hashlib.sha224(password)
enter_password = str(enter_pass_sha.hexdigest())
print 'Password Attempt Hash: ' + enter_password
if stored_password == enter_password:
print 'Password Correct'
else:
print 'Password Incorrect'
You should have noticed this:
Stored Password: cd62248424c8057fea8fff161ec753d7a29f47a7d0af2036a2e79632
# blank line?!
Enter Password: Moo
Password Attempt Hash: cd62248424c8057fea8fff161ec753d7a29f47a7d0af2036a2e79632
Password Incorrect
When you read the stored_password in from the passfile, it comes with a newline character '\n' at the end. You need to do:
with open('pass.txt') as passfile:
stored_password = passfile.read().strip()
print 'Stored Password: ' + stored_password
Note str.strip, called without arguments, removes all whitespace, including newlines, from the start and end of the string. Note also the use of the with context manager for file handling, which handles errors and closes the file for you.
One issue is hexCode = passfile.read - that's a bound method, not a string (you never called it with ()). This will not match any of your strings, and causes an exit from OnPassClick or OnNextClick, or a funny message from OnNewClick. Similarly, you raised the class SystemExit type instead of an instance of it.
Related
I have a very simple 'login' program that I've almost got finished. I'm trying to get my make_acc() function to write the username on line 1 and the password on line 2, as well as make my login() function read those separate lines per what needs to be checked. I'm pretty sure the answer has to do with marking the readline command for which line needs to be read, but I'm not sure how to implement it in my code properly. Here's the code.
# This function has the user input a username for their account
def make_acc():
username = input('Make a username:')
file = open('acc_data.txt','w')
file.write(username)
file.close()
#password = input('Make a password:')
#file = open('acc_data.txt','w')
#file.write(password)
# This function has the user login to a preexisting account
def login():
input_user = input('Enter your username:')
file = open('acc_data.txt','r')
username = file.readline()
if input_user == username:
print('You are now logged in')
else:
print('That user does not exist')
login()
# This variable will be defined as a yes or no depending on whether or not the use has an account
acc_bool = input('Do you already have an account?:')
# This if statement runs the login() function if the user answered yes to the previous input
if acc_bool == 'yes':
login()
# This elif statement runs the make_acc() function if the user answered no to the previous input
elif acc_bool == 'no':
make_acc()
login()
This should do it:
def make_acc():
username = input('Make a username:')
password = input('Make a password:')
with open('acc_data.txt','a') as file:
file.write(username+'\n')
file.write(password)
def login():
input_user = input('Enter your username:')
with open('acc_data.txt','r') as file:
if input_user in [u for i,u in enumerate(file.readlines()) if not u%2]:
print('You are now logged in')
else:
print('That user does not exist')
login()
Instead of having the usernames and passwords all in 2 lines, you can use indexes to determine whether a line is a username or password: even indexes are for usernames, and odd ones are for passwords.
UPDATE:
This part: [u for i,u in enumerate(file.readlines()) if not u%2] lists all the strings in file.readlines() (a list of all the lines in f.read()) if the index of the string, i, doesn't leave a remainder when divided by 2.
You see, enumerate() will basically let us iterate through an array and let use easily access the index of the current iteration.
First, uncomment the part of make_acc that asks for a password and add a file.close().
Then, notice that when you've run the program and inputted the two pieces of information, only one is left in the file, this is because, when calling open(), you use the
w mode, which truncates the file before allowing you to write. The consequence of this is that when you open the file again a couple of lines later, all information previously stored is lost. The solution is to use mode r+ or a or just not close the file until the end of the function, thereby avoiding having to reopening it when writing the password.
Next, when reading from the file, you can use file.readline() just as you already are doing. Choosing what line to read happens by default, because every call to readline advances what line is being read. This means that the second time you call it since you opened the file, the second line will be read.
I am making a login system for my project, and I have the usernames and passwords stored in a text file, with usernames in the first column and passwords in the second column, and then separating each login/password with a new line and using : as a barrier between the username/password.
Upon entering the correct username and password, I always get incorrect login, however if I only compare the username to the file it functions properly. Even if I print the password and username straight from the file and then print it next to the username/password I entered, it is still the exact same yet still say incorrect login!
def login():
file=open("user.txt","r")
user=input("enter usename")
password=input("enter password")
Check=False
for line in file:
correct=line.split(":")
if user==correct[0] and password==correct[1]:
Check=True
break
if Check==True:
print("succesffuly logged in")
file.close()
mainMenu()
else:
print("incorrect log in")
file.close()
login()
I suspect you have a \n at the end of each user / password string. I suspect line looks like user:pass\n after being read in. Use line.strip().split(':') to remove the newline, which is causing password==correct[1] to fail.
Replace:
for line in file:
correct=line.split(":")
With:
for line in file:
correct=line.strip().split(":")
For why, see https://docs.python.org/2/library/string.html#string.strip
string.strip(s[, chars])
Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.
We can just check using in
def login():
file = open("user.txt", "r")
user = input("enter usename ")
password = input("enter password ")
if ('{0}:{1}'.format(user, password)) in file:
print('yay')
else:
print('Boo !! User not found')
login()
if you wanted to use the for loop I would suggest:
def login():
file = open("user.txt", "r")
user = input("enter usename ")
password = input("enter password ")
for line in file:
temp_user, temp_password = line.strip().split(':')
if temp_user == user and temp_password == password.strip():
print('yay')
else:
print('boo username and password not found!')
login()
Really important, WARNING!
Please take necessary security measurements as this code does not provide any, there are a lot of vulnerabilities that could be exploited. No hashing function and Python itself does not provide a lot of security, I would suggest using getpass.getpass explanation HERE
so I am trying to create a program that will allow a user to login using a username and password for a school project. however, my teacher (he has allowed me to ask FYI) wants us to think of a way to make it secure.
so my thought process is that I would allow the user to create a login and store the usernames and passwords in a notepad file. to make these secure I decided to use the hash() function so that the username and passwords couldn't be seen even if the text file was accessed. the issue that I am running into is that I can't figure out how to get the program to see the saved hash version of the username and password in the text file and then compare it to the inputs for longing in without printing the hashes and or saving them as variables.
I can't do this however because if I have more than one login saved in the login file I cant save all the hashed logins as one variable.
if anyone can help it would be greatly appreciated
import sys
import time
print ("welcome to this quiz.")
account = input ("first off do you have a account already. please enter yes or no only").lower
if account == no:
account_create = input ("to continue with this quiz you need a password would you like to create a account. please enter yes or no only").lower
if account_create == no:
print (" the program will close in 30 seconds. if you change your mind come back and make an account")
time.sleep(30)
sys.exit
else:
print ("thank you for creating an account")
username = input ("first off you need a username. please enter a username. be carefull once it is chasen it cant be changed")
# need to add a function that searches the login file and compares no username is repeated
password = input ("secondly you need a password. please choose a password. be carefull you can change it later but you will need the current one to do this.")
username = hash(username)
password = hash(password)
file = open("Login.txt","w")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved. ")
print ("now please login")
else:
login? = input ("would you like to login to the program").lower
if login? == no:
print ("please come back another time")
time.sleep(20)
sys.exit
else:
username_check = input ("please enter your username")
password_check = input ("please enter your username")
username_check = hash(username_check)
password_check = hash(password_check)
file = open("Login.txt","r")
if username_check ==
Load the file as a dictionary mapping usernames (or their hashes) to the hash of the password.
You can iterate through the file and load each line into your dictionary.
However this will be a bit fragile. What if some user want to have a space or comma in their username. A better and easier approach is to use a library to serialize and deserialize the dictionary. The common one used in python would be pickle or if you want the data to still be somewhat human readable json.
I have did a little research around "Google", "YouTube", "Facebook" and "Stack Overflow" and I haven't found what I was looking for. So, I need your guidance. :)
I want program to ask user input "PASSWORD" and every time user inputs wrong password the program asks password again, and again, and again until user
types the correct password. Let's say that the password is as simple as "abc123".
So, I start the program and it asks to input: "PASSWORD: ". If user types "abc123" then program prints "GOOD PASSWORD". If user types anything what is not "abc123" then program prints "BAD PASSWORD". As simple as that.. for now.
My best attempt:
#SECTION1_ASKING
passwordInput=input('PASSWORD: ')
password='abc123'
while password == passwordInput:
print('GOOD PASSWORD')
break
else:
print('BAD PASSWORD')
passwordInput=input('PASSWORD: ')
#SECTION2_RE-ASKING
while False:
while password == paswordInput:
print('GOOD PASSWORD')
else:
print('BAD PASSWORD')
passwordInput=input('PASSWORD: ')
but I either make password asked once or twice or I stuck in Infinite while Loop.
Try this:
passwordInput=raw_input('PASSWORD: ')
password='abc123'
while True:
if password == passwordInput:
print('GOOD PASSWORD')
break
else:
print('BAD PASSWORD')
passwordInput=raw_input('PASSWORD: ')
You can do as below in few lines.
password='abc123'
while(True):
passwordInput=input('PASSWORD: ')
if(passwordInput==password):
print("Good password")
break
else:
print("Bad password")
Here is my solution:
password = 'abc123'
while True:
passwordInput = input('PASSWORD: ')
if password == passwordInput:
print('GOOD PASSWORD')
break
else:
print('BAD PASSWORD')
How does that differ from yours? For a start you can see that I only have one call to input(), that's generally a good idea because then you only need to check the password in one place. Notice that I use if instead of while for the test.
In your second example you have while False:. Can this ever be True? No, so it won't get executed.
Notice as well that I use more whitespace. That does not slow the program down, it makes it easier to read. See also PEP008
Now you have it working, just for fun, consider an improvement. Normally you don't want the password to be visible when it is typed, but there's a module for that: getpass - it's part of the standard library so you don't need to download anything.
Add import getpass to the top of your script. Instead of input use getpass.getpass, in the same place in the program, with the same parameters. Now it won't echo the password entered by the user.
getpass is the module name, getpass is also a function name, so getpass.getpass('PASSWORD: ') means execute the getpass() function in the getpass module. We use lots of modules in Python, so its worth getting used to using them. You can find the documentation here, note there is also a getpass.getuser() to play with.
I wanted to make a simple login system with python 3.5. what it does is opens a document with usernames and passwords inside it. the document has a username on the first line, and the password for that user on the second line. this continues through the document, resulting in usernames on every odd line, and passwords on every even line. the loop goes through all 20 lines (for 10 users) and takes every odd line as a username, and every even line as a password. it goes through, and checks if the username and password are correct. for some reason, it does not work, it just asks to input username, and input password, and doesnt return anything. it is opening the document fine, as it works when i print out the usernames and passwords.
username = input('please enter your username')
password = input('please unter your password')
for i in range(0,20,2):
text_file = open('users.txt','r')
database = text_file.readlines()
if username == database[i] and password == database[i+1]:
print('login accepted')
else:
if username == database[i] and password != database[i+1]:
print('incorrect password')
text_file.close()
The likely problem has more to do with string stripping than anything. Chances are you have a text file like:
myusername
mypassword
otherusername
otherpassword
and when you're reading it you get:
["myusername\n", "mypassword\n", ... ]
You can most likely fix this just by using str.strip on each line read from the file.
However you have a couple more logic errors than this. Here's one:
for i in range(0, 20, 2):
text_file = open(...)
database = text_file.readlines()
# you really want to open the file and read from it EVERY SINGLE LOOP??
and also:
if username == database[i] or password == database[i+1]:
# log in if your password is ANYONE'S password, or if your username
# is ANYONE'S username.
In the grand scheme of things, you should be pre-processing the text file to create a dictionary of key-value pairs.
database = {} # empty dict
with open('path/to/textfile.txt') as inf:
while True:
try:
username = next(inf)
password = next(inf)
except StopIteration:
break
else:
database[username.strip()] = password.strip()
username_in = input("What's your username? ")
password_in = input("What's your password? ")
if database[username_in] == password_in:
# login successful
But REALLY, you should never ever ever ever be storing passwords in plain text for any reason whatsoever. Good lord, man, do some research on password storage! :)
Answer by Adam Smith is great.
I can only add that the line
if database[username_in] == password_in:
might cause a KeyError if there is no such username in your database. You might want to either check if username exists in database before checking passwords or wrap password check in the try except block or use dict.get(key, default) method to get the password from your database
Here some code:
# Pre check
if username_in in database.keys():
if database[username_in] == password_in:
# ...
else:
# No such username in database
# try .. except
try:
if database[username_in] == password_in:
# ...
except KeyError:
# No such username in database
# get with default
# if no default is specified, default is None
if database.get(username_in) == password_in: