How do I use a specific string as my salt and configure the cost factor when hashing using bcrypt in python

Viewed 18

I am new to bcrypt and Im trying to use a specific field on my database to create a has with bcrypt.

what I did so far

import bcrypt

# example password
password = "password123"
accountName = "james"

# converting password to array of bytes
pw_bytes = password.encode('utf-8')

# generating the salt
salt = (accountName.Upper()).encode()

# Hashing the password
pw_hash = bcrypt.hashpw(pw_bytes, salt)

print(pw_hash)

I get this error message

invalid salt

I also want to add the cost factor of 4 and I am not sure how to. Some help will do some good.

1 Answers

As pointed out in the bcrypt Wikipedia article the salt passed to bcrypt.hashpw needs to contain a hash algorithm identifier, cost, as well as a 22 byte salt.

If you wanted to generate your own salt it might look like:

from string import printable
import secrets
import bcrypt


def gen_salt(phrase: str, rounds: int = 12, prefix: bytes = b'2a') -> bytes:
    # choose a random printable byte to use as pad character
    pad_byte = secrets.choice(printable[:62]).encode()
    padded_phrase = phrase.upper().encode().ljust(22, pad_byte)
    cost = str(rounds).encode()
    return b'$' + prefix + b'$' + cost + b'$' + padded_phrase


# example password
password = "password123"
accountName = "james"

# converting password to array of bytes
pw_bytes = password.encode('utf-8')

# generating the salt
salt = gen_salt(accountName)
print("salt:", salt)
# Hashing the password
pw_hash = bcrypt.hashpw(pw_bytes, salt)

print(pw_hash)
Related