Alex Stone
Alex Stone

Reputation: 47354

Python is it possible to check if MD5 string is equal to string in one operation?

I got the following code that compares an MD5 hash from a web service call to a locally stored password (to be retrieved from a database). Is there a better or more secure way to do MD5 string equality checks in python? Maybe hashlib has a function that can take two arguments and return true/false?

md5   = request.values.get('md5')

m = hashlib.md5()
m.update("mypassword")
md5Python = m.hexdigest()

if md5Python == md5:
    #return success

#return fail

Upvotes: 0

Views: 1701

Answers (2)

synthesizerpatel
synthesizerpatel

Reputation: 28056

Instead of retrieving the password from the database to compare against - hash the password you get from the user and make that hash part of your user query?

select uid from users WHERE username = '[email protected]' AND password = '<hash>';

That way you never load the real hashed password into the application and potentially expose it. If you load the entire user record into the application, it increases the potential for information leakage and somewhat defeats the entire point of password hashes.

Also, use AES-512, or AES-256 - md5 isn't good enough anymore.

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168796

The constructor for hashlib.md5 takes an optional string, so you don't need the call to .update():

if md5 == hashlib.md5("mypassword").hexdigest():

Upvotes: 1

Related Questions