i have a stored hash password with bcrypt library so it always stores a different hash string in my db. How can i compare a string value with the store password if they are not the same?
#login.route('/log',methods=['POST'])
def login():
error = None
# get data from JSON
body = request.get_json()
# if data contains something
if body != error:
# Verification of POST method
if request.method == 'POST':
# bucle for empty values findings
validation = all(x != "" for x in body.values())
if validation:
username_mod = body['username']
password_mod = body['password_hash']
forced = b"valentina"
hashed = hashpw(password_mod.encode('utf-8'), gensalt())
userMatch = User.query.filter_by(username=username_mod).first()
store_password = userMatch.password_hash
if checkpw(forced, hashed):
print("it matches")
else:
print("they dont")
if userMatch:
if checkpw(hashed, store_password):
pswd_match = True
else:
pswd_match = False
if userMatch and pswd_match:
return msg_handler("user allowed", 200)
else:
return msg_handler("user denied", 400)
else:
return msg_handler("missing value in 1 or more parameters", 400)
else:
return msg_handler("Must be POST method", 400)
else:
return msg_handler("no data", 400)
im attaching my debug
It looks to me like you're generating a new salt every time you hash the password. The salt is a randomly-generated value that gets attached to the password before it gets hashed.
If you and I both choose abc123 as our passwords, then the hashes of our passwords will be the same too. If someone finds out my password is abc123, and they see that your hash is the same, then they'll know your password too. Now say that my password is abc123 but when it gets hashed, it sticks a few random bytes at the beginning, say 7c6. It then stores both my salt, 7c6, and the hash of 7c6abc123. You still use abc123 as your password, but it randomly generates 9er as the salt for you. It then stores 9er as your salt, and the hash of 9erabc123. Now our hashes look different, even though our passwords are the same.
Note that the salt is stored unencrypted. That's so you can enter your password, it can stick the salt on the front of it, then hash the salt + password combo. That hash is what needs to get compared to the stored hash. If you generate a new salt every time, the hash is going to be different every time.
So, this part:
hashed = hashpw(password_mod.encode('utf-8'), gensalt())
should not generate a new salt. It needs to re-use the salt that was used (and stored) previously.
i solve my problem using werkzeug.security
now my code is like this:
from werkzeug.security import generate_password_hash, check_password_hash
username_mod = body['username']
password_mod = body['password_hash']
userMatch = User.query.filter_by(username=username_mod).first()
store_password = userMatch.password_hash
if userMatch:
if check_password_hash(store_password, password_mod ):
pswd_match = True
else:
pswd_match = False
if userMatch and pswd_match:
return msg_handler("user allowed", 200)
else:
return msg_handler("user denied", 400)
Related
I have user info from a SQL Server - a username and password -
and now I want to create a dictionary
{ID : password}
but if I have more then one it just saves the last one I put in
for i in (cursor.execute('select * from Person')):
idNameDict = {i[0]:i[3]}
I want to do it this way so it would be easier for me to do check if the based on the ID that the password input would be correct because right now and it seems to long
def logIn(userName,userPassword):
userID=[]
global p
lbl = Label(root)
lbl.grid(row=5,column=1)
for user in (cursor.execute('select * from Person')):
p = Person(user[0],user[1],user[2],user[3])
userID.append(p)
for id in userID:
if userName == id.ID:
if userPassword == id.password:
userPage(root,userName)
else:
lbl.config(text= "Invalid Password")
else:
lbl.config(text= "Invalid User Name")
Your current code doesn't work properly because you declare the dictionary from scratch in each iteration. You need to do it in the following way:
idNameDict = {}
for i in (cursor.execute('select * from Person')):
idNameDict[i[0]] = i[3]
database=[['username1','password1'],['username2','password2']]
def check_match():
check_username()
check_password()
for pair in database:
if check_username==pair[0]:
if check_password==pair[1]:
print('login succesful!')
return
else:
print('login failed')
return
This is the code I have currently to check if index 0 of a list matches index 1 of the same list, It's not working though. check_username() and check_password() hold the contents of a list based on user input.
I realized I called the incorrect functions in the given function, that's my bad, thanks for the help though!
Here is a simple answer. You can modify it accordingly but i made it to satisfy the basic needs;
database=[['username1','password1'],['username2','password2']]
username = 'username1'
password = 'password2'
def login(username, password):
for i in range(len(database)):
if username == database[i][0] and password == database[i][1]:
print("login successfull")
return
print("invalid credentials")
login(username, password)
username and password can be taken from the user.
I'm using an online md5 generator to get the hash value of 'football'. When Python converts my input "football" at the prompt it generates a different hash. It then generates another totally different hash from the word "football" thats in my list. So no match when it compares them. I have hashed the word "football" in different online md5 generators and get the same result. Only in Python do i keep getting different results. Thanks for any help.
import hashlib
def dictionary_attack(password_hash):
dictionary = ['letmein', 'password', '12345', 'football']
password_found = None
for dictionary_value in dictionary:
temp_value = hashlib.md5('dictionary_value'.encode('utf-8'))
hashed_value = temp_value.hexdigest()
if hashed_value == password_hash:
password_found = True
recovered_password = dictionary_value
if password_found == True:
print(f'Found match for hashed value: {password_hash}')
print(f'Password recovered: {recovered_password}')
else:
print(f'password not found')
def main():
objhash = input('Enter value: ')
hashobj = hashlib.md5('objhash'.encode('utf-8'))
password_hash = hashobj.hexdigest()
dictionary_attack(password_hash)
if __name__ == '__main__':
main()
You're not computing the hash of "football". You're computing the hash of the string "dictionary_value".
Change the line
temp_value = hashlib.md5('dictionary_value'.encode('utf-8'))
in dictionary_attack to
temp_value = hashlib.md5(dictionary_value.encode('utf-8'))
Likewise, in main, change
hashobj = hashlib.md5('objhash'.encode('utf-8'))
to
hashobj = hashlib.md5(objhash.encode('utf-8'))
I need to assign a unique name that contains the word 'user' and a certain random numbers to a user. Something like user32944, user80890 etc. So I write a program something like this
import random
user_list = ["user32944", "user60690"] # essentially this list is what I retrieve from some database
user_name = ""
while(True):
if user_name not in user_list:
user_name = "user" + str(random.random() * 100000).split(".")[0]
break
print(user_name)
But if I deliberately set the user_name to something that already exists in the list, my program doesn't exit the loop and the program hangs.
What am I doing wrong?
You only perform a action when the generated username is not in the list, but you don't do anything when the username is in the list. And therefore you don't exit the while loop and the program will hang.
The following code sample does what you want. Although i recommend you to explore the uuid package in python.
import random
user_list = ["user32944", "user60690"] # essentially this list is what I retrieve from some database
def generateRandomUsername():
randomNr = random.randint(1,3)
if randomNr == 1:
return "user32944"
else:
return "user" + str(random.random() * 100000).split(".")[0]
def getRandomUniqueUsername():
while(True):
username = generateRandomUsername()
if username not in user_list:
print('Created user \'%s\'' % username)
return username
else:
print("Username \'%s\'already exists, generating new one" % username)
def printUsernameList():
for username in user_list:
print('Username: %s' % username)
#Create 4 random usernames
for i in range(4):
username = getRandomUniqueUsername()
user_list.append(username)
print('Printing user_list...')
printUsernameList()
That will never exit the loop because you are never satisfying the IF condition and there is no conditional expression on while too, you gave True in while condition -> which means it loops infinitely.
So if you do not satsifying the IF condition then write a logic what you would want to do incase IF does not get statisified and then break out of the loop.
And if you want guid with just random alphanumeric ids, then use uuid package in python.
Sorry if the answer to this question may be obvious, but I'm very new to Python (just first started reading a small document about the differing structure and other things from C this morning). While practicing, I decided to make an ATM. However, something weird in the verification process happened, where it compares the input password to the password in a .txt file representing a user database. Despite the two strings are perfectly equal (and yes, I've checked the type, both are class str), my script is completely failing to compare the two correctly! I'm looking and I'm sure I'm missing something obvious, but I just can't find it.
Here's the relevant bits:
class MockUserInterface:
def __init__(self):
ccn = input('Enter your Credit Card Number --> ')
password = input('Enter the corresponding password --> ')
self.db = MockDatabase()
self.processUser(ccn, password)
processUser(self, ccn, password) passes ccn and password to VerifyUser to get a False|dictionary value...
class MockDatabase:
def __init__(self):
self.initdata = open('D:/users.txt', 'r')
self.data = {}
line = 0
for user in self.initdata:
line += 1
splitted_line = user.split(',')
self.data[splitted_line[0]] = {'Name' : splitted_line[1], 'Password' : splitted_line[2], 'Balance' : splitted_line[3], 'id' : line}
self.initdata.close()
def verifyUser(self, ccn, password):
if ccn in self.data:
if ccn == self.data[ccn]['Password']:
return self.data[ccn]
else:
print(password, self.data[ccn]['Password'])
else:
print(self.data)
The users.txt looks like this:
13376669999,Jack Farenheight,sh11gl3myd1ggl3d4ggl3,90001
10419949001,Sardin Morkin,5h1s1s2w31rd,90102
12345678900,Johnathan Paul,w3ll0fh1sm4j3sty,91235
85423472912,Jacob Shlomi,s3ndm35h3b11m8,-431
59283247532,Anon Tony,r34lp0l1t1k,-9999
After running the script, the output is:
C:\Python33\python.exe D:/PythonProjects/ATM(caspomat).py
Enter your Credit Card Number --> 13376669999
Enter the corresponding password --> sh11gl3myd1ggl3d4ggl3
sh11gl3myd1ggl3d4ggl3 sh11gl3myd1ggl3d4ggl3
Process finished with exit code 0
Again, sorry if the answer is obvious or I'm not giving enough info!
You are comparing ccn to the password - not the password arg with the user's stored password...
if ccn == self.data[ccn]['Password']:
should be
if password == self.data[ccn]['Password']: