How to generate an htpasswd bcrypt entry in Python

Create a mock htpasswd file entry with a bcrypt-hashed password for a given username using a simple Python script.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 15 views 0 copies

Requires third-party packages — install first
pip install bcrypt

Python code

10 lines
Python 3.9+
import bcrypt

def mock_htpasswd_entry(username, password):
    salt = bcrypt.gensalt(rounds=12)
    hashed = bcrypt.hashpw(password.encode(), salt).decode()
    return f"{username}:{hashed}"

if __name__ == "__main__":
    entry = mock_htpasswd_entry("demo_user", "s3cretP@ss")
    print(entry)

Output

stdout
demo_user:$2b$12$VhC6vNxBfq8O0JdKx2XfQeWmY2R5Q3Y0qWjZ2lZ7m8yX1oTk2sTfG

How it works

This script uses the bcrypt library to generate a salted hash of the password, which is the format expected in htpasswd files when using bcrypt encryption. bcrypt.gensalt(rounds=12) creates a random salt with 12 hashing rounds, increasing security. The password is encoded to bytes before hashing, then decoded back to a string for display. The final entry is formatted as username:hashed_password, which can be appended directly to an .htpasswd file for HTTP basic authentication on servers like Apache or Nginx.

Common mistakes

  • Forgetting to encode the password string to bytes before passing to `hashpw`.
  • Using `bcrypt.hashpw` without `gensalt` results in an error; always generate a fresh salt.
  • Overwriting the salt with a fixed value for reproducibility, which reduces security.

Variations

  1. Use `bcrypt.checkpw` to verify a plaintext password against an existing hash for authentication.
  2. Read the password from an argument or environment variable instead of hardcoding it.

Real-world use cases

  • Automating creation of `.htpasswd` files for securing web directories in deployment scripts.
  • Generating test credentials for CI/CD pipelines that need HTTP basic auth for staging environments.
  • Managing user accounts for self-hosted services that require htpasswd format for login.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Automation & scripting

Related tutorials and quizzes for this topic.