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.

Santhan Salai
  • 3,888
  • 19
  • 29
Sissi
  • 65
  • 1
  • 10

1 Answers1

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

eddiewould
  • 1,555
  • 16
  • 36
  • 1
    +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. – jeromej May 22 '15 at 01:08