2012-03-04 138 views
23

我想用bcrypt來散列密碼,然後驗證提供的密碼是否正確。如何使用bcrypt將純文本密碼與哈希密碼進行比較?

哈希密碼很簡單:

import bcrypt 

password = u'foobar' 
password_hashed = bcrypt.hashpw(password, bcrypt.gensalt()) 

# then store password_hashed in a database 

我如何比較明文密碼存儲的散列?

回答

44

使用py-bcrypt,你不需要單獨存儲鹽:bcrypt將鹽存儲在散列中。

您可以簡單地使用散列作爲鹽,並將鹽存儲在散列的開頭。

>>> import bcrypt 
>>> salt = bcrypt.gensalt() 
>>> hashed = bcrypt.hashpw('secret', salt) 
>>> hashed.find(salt) 
0 
>>> hashed == bcrypt.hashpw('secret', hashed) 
True 
>>> 
+4

好的答案,但只是一個FYI,'哈希'是一個Python 2和3保留關鍵字(內建函數),並設置'哈希= ...'覆蓋內置的任何範圍內的內置。我會改變它像'hashed'或'pw_hash'等。 – alichaudry 2017-03-29 20:21:11

+0

我同意。這個'hash'必須被其他名稱替代:)。 – ivanleoncz 2017-10-02 21:09:27

+0

不要忘記編碼你的字符串,'secret'.encode()'。注意:在Python 3中測試。 – Yamaneko 2018-02-04 03:15:38

5

稍後,假設您有一個用戶輸入密碼user_pass。你也可以將其散列,然後將散列與存儲的散列進行比較,如果它們匹配,那麼原始密碼也匹配。

請注意,bcrypt會自動將salt值存儲爲散列密碼的一部分,以便您在散列未來輸入時也可以使用它。

第一次圍繞:

import bcrypt 

password = u'foobar' 
salt = bcrypt.gensalt() 
password_hashed = bcrypt.hashpw(password, salt) 

# store 'password_hashed' in a database of your choosing 

後來時間:

import bcrypt 
password = something_that_gets_input() 

stored_hash = something_that_gets_this_from_the_db() 

if bcrypt.hashpw(password, stored_hash) == stored_hash: 
    # password matches 
+0

謝謝。是新來這個,我完全失蹤的事實,鹽和密碼需要被存儲並隨後進行比較。感謝堆! – MFB 2012-03-04 22:56:16

+2

使用bcrypt時不需要存儲鹽。下面的答案是正確的。 – 2013-05-01 02:27:52

11

沒有提到存儲鹽的文檔,它說,你只需要:

#Initial generation 
hashed = bcrypt.hashpw(password, bcrypt.gensalt()) 
#Store hashed in your db 

#Load hashed from the db and check the provided password 
if bcrypt.hashpw(password, hashed) == hashed: 
    print "It matches" 
else: 
    print "It does not match" 

http://www.mindrot.org/projects/py-bcrypt/

+0

每次調用bcrypt.gensalt()時都會生成新的salt,因此必須將salt與bcrypt.hashpw()的結果一起保存。 – skyler 2012-09-03 22:23:02

+6

@skyler - 用bcrypt,鹽被存儲爲散列的一部分。它被保存到散列中,並且自動將散列與它進行比較。 – 2012-10-22 00:31:12