Reputation: 3255
I am using the snippet below to encrypt user password before saving in the database.
from pbkdf2 import crypt
pwhash = crypt(password_from_user)
Example: $p5k2$$Y0qfZ64u$A/pYO.3Mt9HstUtEEhWH/RXBg16EXDMr
Then, I save this in database. Well locally, I can perform a check doing something like this:
from pbkdf2 import crypt
pwhash = crypt("secret")
alleged_pw = raw_input("Enter password: ")
if pwhash == crypt(alleged_pw, pwhash):
print "Password good"
else:
print "Invalid password"
but how do I perform checks with what is on the db as the encrypted string is not always the same. I'm using python-pbkdf2.
Upvotes: 4
Views: 4314
Reputation: 24686
Since python 3.4 you can use the built in hashlib.pbkdf2_hmac
to generate/check pbkdf2 hashes. Here is an example using PBKDF2 with HMAC(sha1):
from hashlib import pbkdf2_hmac
import os
iterations=10000
salt = os.urandom(8) # b'\xd0A,3?\xc5\xe7\xfd' / bytes.fromhex('d0412c333fc5e7fd')
hash = pbkdf2_hmac('sha1',b'secret', salt, iterations, dklen=64).hex()
print(f"pbkdf2:{iterations}:{salt.hex()}:{hash}")
# pbkdf2:10000:d0412c333fc5e7fd:85c5ed63e0a80dc314a3134098d6ecb2facba6a9572bd7795ca9213864ff14245e5ea2787f6af1f4835005a1daa0c555b2f3e9af8dbb3db4ac8ed99fa448503b
Upvotes: 0
Reputation: 3255
Okey, Did more research and figured out that to achieve this, i first have to encrypt the password and save in db.as:
pwhash = crypt("secret",iterations=1000)
which can produce a string like $p5k2$3e8$her4h.6b$.p.OE5Gy4Nfgue4D5OKiEVWdvbxBovxm
and to validate when a user wants to login with same password, i use the function below:
def isValidPassword(userPassword,hashKeyInDB):
result = crypt(userPassword,hashKeyInDB,iterations = 1000)
return reesult == hashKeyInDB #hashKeyInDB in this case is $p5k2$3e8$her4h.6b$.p.OE5Gy4Nfgue4D5OKiEVWdvbxBovxm
this method returns True
if the password is same or False
if otherwise.
Upvotes: 2