簡體   English   中英

如何使用 bcrypt 將純文本密碼與散列密碼進行比較?

[英]How to compare plain text password to hashed password using bcrypt?

我想使用bcrypt來散列密碼,然后驗證提供的密碼是否正確。

散列密碼很容易:

import bcrypt

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

# then store password_hashed in a database

如何將純文本密碼與存儲的哈希值進行比較?

使用 py-bcrypt,您不需要單獨存儲鹽: bcrypt將鹽存儲在哈希中。

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

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

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

#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/

稍后,假設您有一個用戶輸入密碼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

我不熟悉 Python,但我認為您可以使用:
public static boolean checkpw(java.lang.String純文本,java.lang.String散列)

# Check that an unencrypted password matches one that has  
# previously been hashed.
if bcrypt.checkpw(plaintext, hashed):
    print "It matches"
else:
    print "It does not match"

我認為這個會更好:

for i in range(len(rserver.keys())):
    salt = bcrypt.gensalt(12)
    
    mdp_hash = rserver.get(rserver.keys()[i])
    rserver.set(rserver.keys()[i], bcrypt.hashpw(mdp_hash.encode(),bcrypt.gensalt(12) ))

    rsalt.set(rserver.keys()[i], salt)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM