0

I am doing a homework: register() function stores username-md5(password) pairs instead of username-password pairs in dict, then login() function checks whether a pair of username and password is correct or not. But I have problem with the login() if I add 'salt' to the md5 hash: the md5 has different returns when the inputs are same.

import hashlib
salt = '1ha3'
def register (**kw):
    md5DB = {}
    md5 = hashlib.md5()
    for key,value in kw.items():
        origin_str = key + value + salt
        md5.update(origin_str.encode('utf-8'))
        md5DB.update( {key : md5.hexdigest()} )
    return md5DB

def login (user, password,**kw):
    input_str = user + password+ salt
    md5 = hashlib.md5()
    md5.update(input_str.encode('utf-8'))
    md5_result = md5.hexdigest()
    if md5_result == kw[user]:
        print ('Correct')
    else:
        print ('Wrong')

database = {'Mike':'mike2001','Bob':'abcd2010','Alice':'2015alice'}
mydb = register(**database)
print (mydb)
login ('Bob','abcd2010',**mydb)

My login function is supposed to print out "Correct", however the result is "Wrong" as the md5 hash result is different from the corresponding mydb item. Can someone help me with this? Thanks in advance.

3
  • 2
    First of all, you should never use md5 for passwords. Commented May 22, 2015 at 1:02
  • 1
    Don't use md5 for this .. ! Use passlib Commented May 22, 2015 at 1:03
  • For the current implementation, you don't really need keyword arguments - register() can just take a dictionary. Commented May 22, 2015 at 1:11

1 Answer 1

4

Ignoring the issue of whether to use MD5 or not, you can fix the issue by constructing a new MD5 instance for each iteration in regsiter()

i.e.

def register (**kw): md5DB = {} for key,value in kw.items(): md5 = hashlib.md5()
origin_str = key + value + salt md5.update(origin_str.encode('utf-8')) md5DB.update( {key : md5.hexdigest()} ) return md5DB

Sign up to request clarification or add additional context in comments.

1 Comment

+1 I was about to hit Enter when you first said it. Also md5DB[key] = md5.hexdigest() will do the same as md5DB.update( {key : md5.hexdigest()} ) ans is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.