Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...