Generate htpasswd entries with bcrypt

This week I was digging around in the configuration of my webserver.

For some internal pages I am using Basic Auth. Looking at the password hashes I noticed they start with $apr1$.

What is that? The Apache documentation about password formats tells us that this is some kind of MD5 hash.

Thanks, but no thanks (It’s a mystery to me why I decided to use this..).

So let’s strengthen security by using blowfish!

It is possible to create bcrypt hashes using the htpasswd command. This is some utility that ships alongside Apache. I am no Apache user, and I am not willing to install it just for one small task. So what do we do?

There are some alternative implementations of just htpasswd (htpasswd.py in python and Apache::Htpasswd in perl) but they don’t support blowfish as far I can see. Sad. Alternatively, there are a lot of online generators out there. But someone must be totally crazy to use them…

Python to the rescue! If you have the bcrypt package installed, you can use this script to generate the hash:

#!/usr/bin/env python3

import bcrypt

print(
    bcrypt.hashpw(
        input().encode(),
        bcrypt.gensalt(rounds=10)
    ).decode()
)

I am using input() here, so the password won’t show up in plaintext inside the ~/.python_history file when using the interactive prompt.

If you save the script inside some file, you may use it like this to append a new entry:

echo "user:$(./htspass.py)" >> .htpasswd

So long.