Can't verify password using passlib - python

So I'm back working on old project and I cant find whats wrong.
This is the part where the password is first time created, this is from the main script:
def first():
if os.path.isfile("secret.txt"):
folder()
else:
os.system("echo > secret.txt")
password = getpass.getpass("Set your password please --> ")
while len(password) < 4:
print("Password must have more then 4 characters!")
else:
password1 = getpass.getpass("repeat your password please --> ")
while password1 != password:
print("Password don't match")
password1 = getpass.getpass("repeat your password please --> ")
if password1 == password:
a = open('secret.txt', 'w').close()
f = open('secret.txt', 'w')
hashed_password = pbkdf2_sha256.hash(password)
f.write(hashed_password)
os.system("attrib +h secret.txt")
folder()
This is the login script and from here is password checked:
def log_in():
f = open("secret.txt", "r")
Password = f.read()
x = 0
while x < 5:
getPass = getpass.getpass("Password:")
if not pbkdf2_sha256.verify("getPass", Password):
print("Password is invalid")
x = x + 1
else:
f.close()
os.system('cls')
print("Welcome back sir\n")
x = 10
time.sleep(2)
if x == 5:
print("acces denied")
time.sleep(5)
os.system("nothing.bat")
So the problem is when I try to verify the password it says its not correct but the password is the same. In doc it says:
Note that since each call generates a new salt, the contents of the resulting hash will differ between calls (despite using the same password as input):
If this is the problem at .verify() then what should I do?
I'm not sure if this is enough info, if not I will post whole source code
I am probably missing some stupid thing but I just cant seem to find it..

I think the problem is:
if not pbkdf2_sha256.verify("getPass", Password):
Change it to:
if not pbkdf2_sha256.verify(getPass, Password):
You have called a str "getPass" not the password that user input.

Related

bcrypt encryption to encrypt passwords in txt file

I am geting an error when trying to check a password using the bcrypt library. The issue seems to be that the hashed variable should be a plain string without "quotation marks". I've attempted to remove the quotation marks multiple times but the error persists. I am seeking assistance in removing the quotation marks from the "hashed" variable in order to make the bcrypt checkpw function work properly.
#----------------------------------------------------------------
#----------------------------------------------------------------
# import module to dencrypt password
#----------------------------------------------------------------
#----------------------------------------------------------------
import bcrypt
def Log_in():
# Print separator line
print("-"*70)
# Prompt user for email or username and password
msg0 = "Enter your username or your email address"
msg1 = "Enter your password"
user_input = input(f"{msg0:45}| ")
user_pasword = input(f"{msg1:45}| ")
print("-"*70)
# Open and read the text file where the user database is stored
db = open("database.txt",'r')
contant = db.readlines()
email_list = []
username_list = []
password_list=[]
# Check if there's content in the database
if contant == None:
pass
else:
# Split each line of the content by '| ' and append the parts to their corresponding lists
for i in contant:
a, b, c, d = i.split("| ")
email_list.append(a.strip())
username_list.append(b.strip())
password_list.append(d.strip())
# Close the file
db.close()
# Check if the entered email or username exists in the email_list or username_list
if user_input in username_list or user_input in email_list:
x = None
y = None
# Try to get the index of the entered email or username in the email_list and username_list
try:
x = username_list.index(user_input)
except:
pass
try:
y = email_list.index(user_input)
except:
pass
if x != None and y == None:
# If the entered username exists in the username_list
# Strip the 'b' character, encode the string to utf-8 and compare it with the entered password
hashed = password_list[x].strip('b')
# hashed = hashed.replace("'","")
hashed = hashed.encode('utf-8')
if bcrypt.checkpw(user_pasword.encode('utf-8'), hashed):
print("Welcome")
else:
print("incorrect password")
Log_in()
elif y != None or x == None:
# If the entered email exists in the email_list
# Remove the double quotes and compare it with the entered password
hashed = password_list[y][:-1]
hashed = hashed.replace('"','')
# hashed1 = hashed.replace(b"\n", b"")
if bcrypt.checkpw((user_pasword.encode("utf-8")),hashed): #error happening here
print("Welcome")
else:
print("incorrect password")
Log_in()
else:
print("incorrect password")
Log_in()
else:
# If the entered email or username doesn't exist in the email_list or username_list
print("This username or the email does not exist")
Log_in()
# main function
if __name__ == "__main__":
Log_in()

Comparing password cell to username cell in excel using python

I am new to python and i'm trying to build my first accounts projects, which i allow users to input name, username, password and other details.
to sign in i would ask user for username and password, i do know how to search in a specific column to check if the username exist, but what im struggling to find is how to check if the password in the same row of the username is correct, i dont want it to search in all passwords column, only the password of the username that has been entered.
i am using open openpyxl for this.
heres my code
def username_check(filename , minrow, maxrow, mincol, maxcol, name):
wd = load_workbook(filename)
ws = wd.active
for row in ws.iter_cols(min_row=minrow,max_row=maxrow,min_col=mincol, max_col=maxcol, values_only=True):
if name in row:
return True
else:
return False
this is the checking function ive made.
while True:
if x == 1:
username = input("enter your account username: ")
password = int(input("enter password: "))
usernamecheck = username_check("accounts.xlsx", 2 , len(ws["C"]), 3, 3, username)
passwordcheck = username_check("accounts.xlsx", 2, len(ws["D"]), 4, 4, password) # This is wrong
if usernamecheck and password == True:
print("ok")
break
this is the code and what im trying to do
enter image description here
this is the table
Its not good practice to 'do' things that take a lot of processing more than once if its not necessary. Making two calls to the function username_check which opens the excel file should be avoided since you can check both the username and password at the same time.
Also be careful of indentation in python code.
You can make the code much simpler and easier to read by using zip to iterate both columns at the same time.
from openpyxl import load_workbook
def username_check(filename, username, password):
wb = load_workbook(filename)
ws = wb.active
for user_col, pass_col in zip(ws['C'], ws['D']):
if user_col.row == 1: # This skips the Header row
continue
if user_col.value == username and pass_col.value == password:
return True
return False
filename = 'accounts.xlsx'
while True:
username = input("enter your account username: ")
password = int(input("enter password: "))
usernamecheck = username_check(filename, username, password)
if usernamecheck:
print("ok")
break

Python program to register accounts an log in

So I'm making a program where I need a user to log in or register. The registered account goes to a .txt file from which I'm supposed to read the data to log in again.
I managed to get the basics working. I can register a new account to the file and I can log in with every account I've created, but I can't seem to get 2 important elements working. The first one is for when the user inserts an inexistent username/ password (in this case the program just does nothing as I can't figure out a condition to make it go back to asking the username and password), and the second one is for when I insert a username and password that don't match. Here the program goes back and asks for them again but then keeps asking, even if I put them correctly.
Here's my function if anyone's interested in having a look at it:
def ent():
util = False
ppass = False
login = False
while not login:
n_util = input("Introduce your username: ")
password = input("Introduce your password: ")
with open("dadoscontas.txt", "r") as f:
while not util:
vski = 0
for line in f:
vski += 1
if vski == 1:
if line.strip() == n_util:
util = True
else:
break
if vski == 2:
if line.strip() == password and user:
ppass = True
if user and ppass:
login = True
print("Logged in")
I've spent my whole afternoon trying different things to see if I can get these 2 things to work, but I can't. As I said, the function above is the part that kinda works, and if anyone could give any suggestions / point me in the right direction it would be really helpful. Thank you in advance.
Does this code cover your needs?
def ent():
util = False
login = False
while not login:
n_util = input("Introduce your username: ")
password = input("Introduce your password: ")
with open("some_test.txt", "r") as f:
vski = 0
for line in f:
vski += 1
if vski%2:
if line.strip() == n_util:
util = True
elif util:
if line.strip() == password:
login = True
else:
util = False
print("Logged in")
Or you even could exit the function with return in if line.strip() == password: block.
But i would recommend you to store the file content to dictionaries (user_name:passwor),
because you are parsing the whole file again and again while login=False:
def ent():
login = False
name=""
my_data = {}
with open("some_test.txt", "r") as f:
index = 0
for line in f:
index += 1
if index%2:
name = line.strip()
else:
my_data[name] = line.strip()
while not login:
n_util = input("Introduce your username: ")
password = input("Introduce your password: ")
if n_util in my_data and my_data[n_util] == password:
login = True
print("Logged in")
If you use python2 you can use .get() or try instead of n_util in my_data for better performance.

Python Login and Register System using text files

Hey I am trying to create a system using text files where a user can sign up and log in. All the data will be stored in plain text in a text file called User_Data.txt. My code works but I would like to know if there is anything I missed or If I could improve it in any way. Sorry for the Bad code Formatting in advance.
def choices():
print("Please choose what you would like to do.")
choice = int(input("For Sigining Up Type 1 and For Signing in Type 2: "))
if choice == 1:
return getdetails()
elif choice == 2:
return checkdetails()
else:
raise TypeError
def getdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
if name in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("User_Data.txt",'w')
info = info + " " +name + " " + password
f.write(info)
def checkdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
info = info.split()
if name in info:
index = info.index(name) + 1
usr_password = info[index]
if usr_password == password:
return "Welcome Back, " + name
else:
return "Password entered is wrong"
else:
return "Name not found. Please Sign Up."
print(choices())
There is a lot of improvements You could do.
First of all, split functionality to smaller function.
PASSWORD_FNAME = "User_Data.txt"
def get_existing_users():
with open("r", PASSWORD_FNAME ) as fp:
for line in fp.readlines():
# This expects each line of a file to be (name, pass) seperated by whitespace
username, password = line.split()
yield username, password
def is_authorized(username, password):
return any((user == (username, password) for user in get_existing_users())
def user_exists(username):
return any((usr_name == username) for usr_name, _ in get_existing_users())
# above is equivalent of:
#
# for usr_name, _ in get_existing_users():
# if usr_name == username:
# return True
# return False
def ask_user_credentials():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
return name, password
def checkdetails():
name, password = ask_user_credentials()
if is_authorized(name, password):
return "Welcome Back, " + name
if user_exists(name):
return "Password entered is wrong"
return "Name not found. Please Sign Up."
def getdetails():
name, password = ask_user_credentials()
if not user_exists(name):
return "Name Unavailable. Please Try Again"
# Not sure tho what would You like to do here
It's always good to remember to always close your file if you read it.
So if you do something like:
f = open("r", "file.txt") remember to always call f.close() later.
If you use context manager and do it like:
with open("r", "file.txt") as fp:
print(fp.read())
it will automatically close the file for you at the end.
Firstly, fix the spelling error at int(input("For Sigining Up Type 1") Other than that I would add some kind of purpose, for example storing secret numbers or something.
For example you can extend your script with a simple password recovery system.
I think it could be useful to learn...
You can implement a sort of a simple hashing system in order to avoid saving the password as plain text.
If you want to add a GUI, please consider using Tkinter.
https://docs.python.org/3/library/tkinter.html
Let we know.
Good Luck and Keep Coding with <3

csv - Creating a login system, python not properly reading from .csv file?

I am trying to make a login system that is looped basically and whenever I try to enter the correct details that are even stored in the .csv file, it outputs as incorrect username/password no matter what I put. This code works for python 3.6 but I need it to work for python 3.2.3.
loop1 = False #for this bit of code (logging in)
loop2 = False #for next bit of code
while loop1 == False:
choice = input("Login/SignUp [TYPE 'L' OR 'S']: ").lower()
if choice == "l":
username = input("Username: ")
password = input("Password: ")
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
#this whole bit of code is meant to read from the csv and check if the login details are correct
else:
print("Username/Password [INCORRECT]")
Allow me to refactor your code:
def login(username, password):
with open("usernamepassword.csv", "r") as csv:
all_details =
[[attr.strip() for attr in line.split(",")]
for line in csv]
return any(
username == details[0]
and password == details[1]
for details in all_details)
def login_action():
username = input("Username: ")
password = input("Password: ")
if not login(username, password):
raise ValueError("Username/Password [INCORRECT]")
return True
_USER_ACTIONS = {
'l': login_action
}
def main():
while True:
choice = input("Login/SignUp [TYPE 'L' or 'S']: ").lower()
action = _USER_ACTIONS[choice]
try:
if action():
break
except Exception as err:
print(err.message)
I think your unexpected behavior comes from not stripping the values you get after splitting by ,
Solved by replacing:
if username == details[0] and password == details[1]:
With:
if username == details[0] and (password+"\n") == details[1]:
You may have a bug in line.split(','), try line.strip().split(',')
TL; DR: posted a proper solution there : https://github.com/cgte/stackoverflow-issues/tree/master/47207293-csv-dict
I'll stuff up my answer later if needed.
Furthermore you have a poor code design here, and find yourself debugging in the middle of a loop.
So first of all : load the data file, store content to a dict.
f = open("usernamepassword.csv","r")
for line in f:
details = line.split(",")
if username == details[0] and password == details[1]:
print("Welcome")
break
Should become
user_pass = {}
f = open("usernamepassword.csv","r")
for line in f:
user, password = line.strip().split(",")
user_pass[user] = password
f.close()
or better
with open("usernamepassword.csv","r") as f:
for line in f.readlines():
user, password = line.split().split(",")
user_pass[user] = password
eventually run python -i yourfile.py and type "user_pass" to see what is actually stored when correct go on further code.
Think of using the csv module : https://docs.python.org/3/library/csv.html
Then get username and password from input and check:
if login in user_pass and user_pass[login] = password:
# or better `if user_pass.get(login, None) == password:`
do_stuff()

Categories