0

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()
1
  • 3
    Because you're generating a new salt every time. Commented Feb 4, 2021 at 17:37

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.