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.
pip install bcrypt
Python code
10 linesimport 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
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
- Use `bcrypt.checkpw` to verify a plaintext password against an existing hash for authentication.
- 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
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.