2015-10-14 143 views
3

我在保存到數據庫之前使用下面的代碼片段來加密用戶密碼。驗證python-pbkdf2中的PBKDF2密碼哈希

from pbkdf2 import crypt 
pwhash = crypt(password_from_user) 

實施例:$p5k2$$Y0qfZ64u$A/pYO.3Mt9HstUtEEhWH/RXBg16EXDMr

然後,我保存此在數據庫中。那麼在當地,我可以執行檢查做這樣的事情:

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" 

但如何執行與什麼是對數據庫的檢查作爲加密字串並不總是相同的。我正在使用python-pbkdf2

+0

https://www.dlitz.net/software/python-pbkdf2/ –

+1

你是什麼意思*「並不總是相同的」*?驗證是否僅僅有時會起作用,還是總是適用於某些密碼,而不適用於其他密碼? –

回答

1

歐凱,做了更多的研究和揣摩,要實現這一目標,我首先對密碼進行加密,並保存在db.as:

pwhash = crypt("secret",iterations=1000) 

能產生像$p5k2$3e8$her4h.6b$.p.OE5Gy4Nfgue4D5OKiEVWdvbxBovxm

和一個字符串當用戶希望用相同的密碼來登錄驗證,我使用下面的函數:

def isValidPassword(userPassword,hashKeyInDB): 
    result = crypt(userPassword,hashKeyInDB,iterations = 1000) 
    return reesult == hashKeyInDB #hashKeyInDB in this case is $p5k2$3e8$her4h.6b$.p.OE5Gy4Nfgue4D5OKiEVWdvbxBovxm 

此方法返回True如果密碼是SA否則我或False