Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

python - bcrypt different hash for same string?

I have created users in mysql with the same password then this code snippet changes the plain text passwords to a hash using bcrypt. Why is the hash different for the same string?

import mysql.connector
import bcrypt

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="........",
    database="briandb",
)
mycursor = mydb.cursor()

for user in ["bob", "alice"]:
    password = "ttt"
    print(password)
    hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt())
    print(hashed)
    mycursor.execute(
        f'UPDATE users set password = "{hashed}" where user = "{user}"'
    )
    mydb.commit()
question from:https://stackoverflow.com/questions/66050881/bcrypt-different-hash-for-same-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've discovered a key feature of robust password hashing: Each time you hash a password you get a different result. Why?

A different random salt (from bcrypt.gensalt() here) is used each time.

Why is this important?

If a cybercreep breaks into your system and steals your users table, they'll have your salted hashed passwords. When the hashing is done correctly, it is very difficult to recover the unsalted passwords. If they, next, break into a bank's system and steal their hashed passwords, we don't want them to be able to conclude that certain users have the same password on both systems. If they could guess that, they'd know which users to target for deeper cybercrimes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...