Reputation: 16392
For a programming exercise I designed for myself, and for use in a pretty non-secure system later on, I'm trying to compare MD5 hashes. The one that is stored in a plain text file and is pulled out by the check_pw()
function and the one that is created from the submitted password from a CGI form. md5_pw(
) is used to create all the hashes in the program.
For some reason, if (pair[1] == md5_pw(pw))
always fails, even though my program prints out identical hashes in my error checking lines:
print "this is the pw from the file: ", pair[1], "<br />" print "this is the md5 pw you entered: ", md5_pw(pw), "<br />"
Where am I messing up?
Code:
def md5_pw(pw):
"""Returns the MD5 hex digest of the pw with addition."""
m = md5.new()
m.update("4hJ2Yq7qdHd9sdjFASh9"+pw)
return m.hexdigest()
def check_pw(user, pw, pwfile):
"""Returns True if the username and password match, False otherwise. pwfile is a xxx.txt format."""
f = open(pwfile)
for line in f:
pair = line.split(":")
print "this is the pw from the file: ", pair[1], "<br />"
print "this is the md5 pw you entered: ", md5_pw(pw), "<br />"
if (pair[0] == user):
print "user matched <br />"
if (pair[1] == md5_pw(pw)):
f.close()
return True
else:
f.close()
print "passmatch a failure"
return False
Upvotes: 0
Views: 276
Reputation:
My guess is that there's an problem with the file loading/parsing, most likely caused by a newline character. By paring your code down, I was able to find that your logic was sound:
def md5_pw(pw):
m = md5.new()
m.update("4hJ2Yq7qdHd9sdjFASh9"+pw)
return m.hexdigest()
def check_pw(pw):
pair = ("c317db7d54073ef5d345d6dd8b2c51e6")
if (pair == md5_pw(pw)):
return True
else:
return False
>>> import md5
>>> check_pw('fakepw')
False
>>> check_pw('testpw')
True
("c317db7d54073ef5d345d6dd8b2c51e6" is the md5 hash for "4hJ2Yq7qdHd9sdjFASh9testpw")
Upvotes: 1
Reputation: 994371
Your pair[1]
probably has a trailing newline. Try:
for line in f:
line = line.rstrip()
pair = line.split(":")
# ...etc
Upvotes: 2