Search code examples
pythonmysqltkintermd5hashlib

MD5 Hash function changing data in Python


I'm trying to make a Login programme in Python using the Tkinter GUI, and using hashlib MD5 to hash the password. Here is my code for Account Creation.

def AccountEntry():
    tk.Label(m, text = "Account Creation").grid(row =2 ,column =1)
    tk.Label(m, text = "Enter name").grid(row = 3, column = 0)
    ename = tk.Entry(m)
    ename.grid(row = 3, column = 1)
    tk.Label(m, text = "Enter password").grid(row = 4,column = 0)
    epassword = tk.Entry(m, show = "*")
    epassword.grid(row = 4, column = 1)
    tk.Button(m, text = "Submit", command = lambda:Account(epassword,ename)).grid(row = 5, column = 1)

def Account(epassword,ename):
    name = ename.get()
    password = epassword.get()
    bytepass = bytes(password, 'utf-8')
    hexpass = str(hashlib.md5(bytepass))
    enter_table = (name,hexpass)
    cursor.execute("insert into lusers(name, hexpass) values(%s,%s)",(enter_table))
    db.commit()
    tk.Label(m, text = "Successfully made account").grid(row = 6, column = 1)

The problem is basically that the md5 function returns different values. So the first time I press "submit" it returns 'md5 HASH object @ 0x03845C68' but it returns 'md5 HASH object @ 0x03845DE8' from the second time onwards when I press "submit" with the same name and password. This creates a problem as in order to Login, the programme takes the password, uses the hash function again and then compares the new hash object to the one in the database, which are different since it messes up the values in the Account Creation.

I suspect that the str(hashlib.md5(bytepass)) could have something to do with it since it was doing the same thing in the Login until I removed str(), but I need to convert the hash object to a string to put it in MySQL.


Solution

  • You aren't getting the md5 hash from that call; you are getting an object that has a method that can return the md5 hash.

    hexpass = hashlib.md5(bytepass).hexdigest()