i am trying to implement a encryption into my login program, i've looked for help in many places but i can't seem to understand any of it.
Im fairly new to python and im warming up for a university course in it.
im interested in if it is possible to implement it as a class in my already excisting program, any tips or explanations would be greatly appreciated
So basicly what im asking is, how would it look if i wanted the program to encrypt the passwords between runs and the decrypt them again so that the program can use them when it runs.
Program:
import json
with open("login_data.txt", "r") as login_file:
try:
users = json.load(login_file)
except:
users = {}
status = ""
def Display_Menu():
status = input("Are you a registered user? (y/n)? Press q to quit: ")
if status == "y":
Old_User()
elif status == "n":
New_User()
elif status == "passwd":
Change_Passwd()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
def New_User():
Create_Login =input("Create login name: ")
if Create_Login in users:
print ("Login name already exist!")
else:
Create_Password =input("Create password: ")
users[Create_Login] = Create_Password
print("New User created!")
current_user = None
def Old_User():
global current_user
login =input("Enter login name: ")
Password =input("Enter password: ")
if login in users and users[login] == Password:
print("Login successful!")
current_user = login
status = input("Wanna quit, change pass, och logout?")
if status == "passwd":
Change_Passwd()
elif status == "logout":
Display_Menu()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
else:
print("User doesn't exist or wrong password!")
def Change_Passwd():
oldpass =input("Old password: ")
if current_user in users and users[current_user] == oldpass:
Create_Password = input("New password: ")
users[current_user] = Create_Password
if Create_Password == input("Confirm password: "):
print("Password changed!")
else:
print("User authorization failure")
users[current_user] = oldpass
else:
print ("No password match!")
while status != "q":
status = Display_Menu()
MD5 is a really simple hashing algorithm, this is some sample usage:
>>> hashlib.md5("String you want to encrypt").hexdigest()
'096a773d70e934d03ae3dd8022deed5e'
MD5 is by no means secure, but it is sufficient to illustrate some points. You could for instance store usernames and hashed passwords in some format of your choosing, ie.:
username1, hash1
username2, hash2
This (Difference between Hashing a Password and Encrypting it) could be a relevant read.
bcrypt is a library you should have a look at.
import bcrypt
password = b"super secret password"
# Hash a password for the first time, with a randomly-generated salt
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
# Check that a unhashed password matches one that has previously been
# hashed
if bcrypt.hashpw(password, hashed) == hashed:
print("It Matches!")
else:
print("It Does not Match :(")
Related
How can I stop the users who have already logged in cant login any more?
I tried to make a variable equal to True
when the user is logged in and make an if statement But it didnt work
if islogin == True:
print("You are already logged in!")
Heres my code
import json
def login():
user = input("Enter your user name: ")
passw = input("Enter your password: ")
with open("info.json") as f:
dct = json.load(f)
if user in dct and dct[user] == passw:
print("Login succesful!")
else:
print("Error! Incorrect username or password.")
return
while True:
demand = input("What do you want to do? ")
if demand == "login":
login()
elif demand == "exit":
break
else:
print("Error")
if you have a unique user try to create a global list for logged user somting like this:
import json
logged_user=[]
def login():
global logged_user
user = input("Enter your user name: ")
passw = input("Enter your password: ")
with open("info.json") as f:
dct = json.load(f)
if user in dct and dct[user] == passw and user not in logged_user:
print("Login succesful!")
logged_user.append(user)
else:
print("Error! Incorrect username or password or .....")
return
while True:
demand = input("What do you want to do? ")
if demand == "login":
login()
elif demand == "exit":
break
else:
print("Error")
How would I put "if" or "else" in code like this?
user = input('Login: Username\n')
time.sleep(1)
password = input('Login: Password\n')
print('Welcome, %s.' % user)
I think this is what you want to do. But this is not a secure way of doing password requests.
user = input('Login: Username\n')
password = input('Login: Password\n')
users = {"You" : "1234", "Me" : "abcd"}
if user in users.keys():
if users[user] == password:
print("Welcome, {u}".format(u=user))
else:
print("Wrong password")
else:
print("This user does not exist")
Here is a simple version on how this should work but is not secure at all, but functions (almost) the same way as you requested (came up with this under 5 mins)
user = input('Login Username: ')
password = input('Login Password: ')
if user == ("Your username here"):
if password == ("Your password here"):
print("Welcome ", user)
Also you do not need "time.sleep()" as it only slows down your code
The code is meant to be a simple login code that saves the login information to a .txt file and then when logging in reads the text file to check the user details.
The code runs up until I create an account or try to login and put in my username and password then it comes back with None. I don't understand why it's coming back with None
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
loginexisting()
elif account == "N":
createacc()
else:
print("please type Y or N")
AskAccount()
def loginexisting():
print("Your account already exists, please login\n")
username = input("Please enter your username:")
password = input("Please enter your password:")
f = open('accounts.txt', 'r')
info = f.read()
info = info.split()
if username in info:
index= info.index(username) +1
usr_password = info[index]
if usr_password == password:
return "Welcome Back," + username
else:
return "password entered is wrong"
else:
print("Username is not correct")
print(createacc())
def createacc():
print("Lets create an account for you\n")
username = input("Please input your username:\n")
password = input("please input your password\n")
f = open("accounts.txt",'r')
info = f.read()
if username in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("accounts.txt",'w')
info = info + " " + username + " " + password
f.write(info)
f.close()
print("Your account details have been saved\n")
print("please login\n")
print(AskAccount())
At the end of your file, you print(AskAccount()). This prints the return value of the function, but AskAccount does not have a return statement, thus it returns None. If you want it to print your desired output, you will need to add return statements.
def AskAccount():
account = input("\nDo you have an account setup
already? (Y/N)\n")
if account == "Y":
return loginexisting()
elif account == "N":
return createacc()
else:
print("please type Y or N")
return AskAccount()
I was wondering if anyone would help. I am new to python. I am trying to create a basic login script for a game, that will write a username and password to a text file. When logging in, it will read from that text file and compare the entry made by the user. The code is below:
def Register():
print("Hello! You need to register an account before you can begin")
username = input("Please enter a username: ")
password = input("Now please enter a password: ")
file = open("Login.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()
print ("Your login details have been saved. ")
print("You will now need to login")
Login()
def Login():
print("Please enter your details to log in")
username1 = input("Please enter your username: ")
password1 = input("Please enter your password: ")
file = open("Login.txt","r")
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
print(username,password)
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
#file.close()
user=input("Are you already a user? ")
if user == "Yes":
Login()
elif user =="No":
Register()
print("Welcome to our game")
I have entered the second user who is stored in the text file, It seems to be working but it checks my first entry and says its incorrect and then loops to the second entry. This is the output I keep getting:
Are you already a user? Yes
Please enter your details to log in
Please enter your username: jen
Please enter your password: ben
tess bess
incorrect
jen ben
Hello jen
Welcome to the dice game
>>>
Does anyone have an idea on how to only display the entry you have entered?
Thanks
Like Sharku said, put the print(username,password) in your if below. Also writting clearly the name and password of the user after he typed it isn"t really a smart moove, delete it and just let your message when a user is logging in !
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
else:
print("incorrect")
As said by sytech, you could use the break and else clauses of the for loop:
for row in file:
field = row.split(",")
username = field[0]
password = field[1]
lastchar = len(password)-1
password = password[0:lastchar]
if username1 == username and password1 == password:
print("Hello",username)
break
else:
print("incorrect")
Your 'for loop' will loop through each entry in your file, that means for each entry in the file your for loop prints the entry due to this line:
print(username,password)
If you don't want it to print all values in the file remove this line of code.
Adding a 'break' to your if statement, as suggested by others, will mean that as soon as your loop has found the entry that matches the one entered by the user it will leave the loop and not continue going through all values unnecessarily.
You could do something like this:
if username1 == username and password1 == password:
print("Hello",username)
break
else:
continue
This means that when a user input doesn't match an entry in the file the loop will just continue till it finds a match.
However, your code doesn't take into consideration if a user doesn't exist.
import os.path
if not os.path.exists('register.txt'):
file = open('register.txt', 'w')
file.close()
def register():
username = input('Enter username: ')
if username in open('register.txt', 'r').read():
print('Username already exists')
exit()
password = input('Enter password: ')
c_password = input('Enter confirm password: ')
if password != c_password:
print('Sorry password not match')
exit()
handle = open('register.txt', 'a')
handle.write(username)
handle.write(' ')
handle.write(password)
handle.write('\n')
handle.close()
print('User was successfully registered')
exit()
def login():
username = input('Enter username: ')
password = input('Enter password: ')
get_data = open('register.txt', 'r').readlines()
users_data = []
for user in get_data:
users_data.append(user.split())
total_user = len(users_data)
increment = 0
login_success = 0
while increment < total_user:
usernames = users_data[increment][0]
passwords = users_data[increment][1]
if username == usernames and password == passwords:
login_success = 1
increment += 1
if login_success == 1:
print('Welcome ' + username)
else:
print('invalid username & password')
question = input('Do you have an account?/yes/no')
if question == 'yes':
login()
else:
register()
Hi. I am trying to make a program that is able to create users and then log them in. Once you're logged in you can change your password. What I can't seem to figure out is how to get it to change your password after you logged in, using only your old password. I can get it to work by inputting your account name, but that's not the point.
Do any of you have any idea of how to fix this problem, I am open to suggestions :)
import json
with open("login_data.txt", "r") as login_file:
try:
users = json.load(login_file)
except:
users = {}
status = ""
def Display_Menu():
status = input("Are you a registered user? (y/n)? Press q to quit: ")
if status == "y":
Old_User()
elif status == "n":
New_User()
elif status == "passwd":
Change_Passwd()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
def New_User():
Create_Login =input("Create login name: ")
if Create_Login in users:
print ("Login name already exist!")
else:
Create_Password =input("Create password: ")
users[Create_Login] = Create_Password
print("New User created!")
def Old_User():
login =input("Enter login name: ")
Password =input("Enter password: ")
if login in users and users[login] == Password:
print("Login successful!")
print(users[login])
status = input("Wanna quit, change pass, och logout?")
if status == "passwd":
Change_Passwd()
elif status == "logout":
Display_Menu()
elif status == "q":
skriva = open("login_data.txt", "w")
json.dump(users, skriva)
return status
else:
print("User doesn't exist or wrong password!")
def Change_Passwd():
oldpass =input("Old password: ")
if oldpass in users:
Create_Password =input("New password: ")
users[oldpass] = Create_Password
if Create_Password == input("Confirm password: "):
print("Password changed!")
else:
print("User authorization failure")
users[create_Login] = oldpass
else:
print ("No password match!")
while status != "q":
status = Display_Menu()
A example of a account file " { "halo": "molly"} "
The minimal change would be to save the currently logged in user to a global variable in Old_User(). Then, when Change_Passwd is called, you can go back to that variable to determine which user you're dealing with. Here's the changes you'd make to Old_User. I'll leave the changes to Change_Passwd up to you to implement.
current_user = None # Declare global variable for saving logged in user
def Old_User():
global current_user # Indicate that we're going to modify the global variable in the local scope
login =input("Enter login name: ")
Password =input("Enter password: ")
if login in users and users[login] == Password:
print("Login successful!")
print(users[login])
current_user = login # Save the logged in user.
...
I should also add that you'd be better served using classes for this. Trying to maintain state (like who the current user is) using global variables is not very scalable and can get confusing pretty quickly. Having classes representing users and active sessions would make things easier.