Question

import bcrypt

hashedstring = bcrypt.gensalt()
password = bcrypt.hashpw(password,hashedstring)

Should I save the hashedstring everytime in the database table field to login succeesfully next time getting the hashed string?

Or should I use a static pre-generated hashed string in code?

Was it helpful?

Solution

The salt you use to hash the password is stored in the resulting hash - this means there is no need to store it in the database, as it can be recovered from the hash.

According to the project page, this can be done like so:

# Store a hash.
import bcrypt
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
store_in_db(user, hashed) #Where user is the user to load the hash for, and store_in_db does what it says on the tin.

# Check against an existing hash
import bcrypt
hashed = load_from_db(user) # (get the password of the user from database) Where user is the user to load the hash for, and load_from_db does what it says on the tin.
if bcrypt.hashpw(password, hashed) == hashed: # Where password is a plaintext password attempt.
        print "It matches"
else:
        print "It does not match"

And yes, you should use a different salt for each value - which BCrypt's design encourages.

OTHER TIPS

Short answer: Use a new salt for each password. (EDIT: with bcrypt you needn't store the salt separately)

Imagine if an attacker gets the password database from a website. If all the passwords are hashed using a common salt, then the attacker can easily find people using common passwords:

hashedpwd = somehash('swordfish' + salt)

Then just a database query is needed to find everyone using 'swordfish' as a password. There will always be a substantial fraction of users with quite common passwords.

On the other hand, if every password has its own salt, and there are 1 million passwords in the database, an attacker must calculate 1 million hashes in order to check just one password, so it's much more secure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top