Skip to content

Instantly share code, notes, and snippets.

@zobayer1
Created January 25, 2021 21:17
Show Gist options
  • Save zobayer1/d86a59e45ae86198a9efc6f3d8682b49 to your computer and use it in GitHub Desktop.
Save zobayer1/d86a59e45ae86198a9efc6f3d8682b49 to your computer and use it in GitHub Desktop.
Bcrypt password generator for htpasswd with Python

Generator:

# file: gen.py

import bcrypt

def encrypt_password(username, password):
    bcrypted = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12)).decode("utf-8")
    return f"{username}:{bcrypted}"

print(encrypt_password("client", "ClientO98"))

Test with htpasswd:

$ python gen.py > passwd
$ htpasswd -vb passwd client ClientO98
Password for user client correct.
$ htpasswd -vb passwd client ClientO99
password verification failed
$ htpasswd -vb passwd client1 ClientO98
User client1 not found
@zobayer1
Copy link
Author

Additionally, if you need to replace 2b or 2y to 2a, you can add this line before returning:

bcrypted = re.sub(r"\$2[^a]\$", "$2a$", bcrypted)

@antifuchs
Copy link

Better yet, instead of doing that gsub, use the prefix arg to the gensalt function:

def encrypt_password(username, password):
    bcrypted = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12, prefix=b"2a")).decode("utf-8")
    return f"{username}:{bcrypted}"

(You can drop the rounds=12 parameter too, as it already defaults to 12.)

@zobayer1
Copy link
Author

Better yet, instead of doing that gsub, use the prefix arg to the gensalt function:

def encrypt_password(username, password):
    bcrypted = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=12, prefix=b"2a")).decode("utf-8")
    return f"{username}:{bcrypted}"

(You can drop the rounds=12 parameter too, as it already defaults to 12.)

The prefix arg is indeed much cleaner. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment