Skip to content

Instantly share code, notes, and snippets.

@ckujau
Last active August 26, 2023 22:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ckujau/2197c7b7aa773cd9b930e7e68b051a6d to your computer and use it in GitHub Desktop.
Save ckujau/2197c7b7aa773cd9b930e7e68b051a6d to your computer and use it in GitHub Desktop.
Generate an .htpasswd file without the Apache tools
#!/bin/bash
#
# Generate an SSHA password for .htpasswd files
# * https://www.nginx.com/resources/wiki/community/faq/#how-do-i-generate-an-htpasswd-file-without-having-apache-tools-installed
# * https://nginx.org/en/docs/http/ngx_http_auth_basic_module.html#auth_basic_user_file
#
if [ -z "$1" ]; then
echo "Usage: $(basename $0) [user]"
exit 1
else
NAME="$1"
read -p "Password: " -s PASSWORD
echo
fi
SALT=$(openssl rand -base64 3)
SHA1=$(echo -n "${PASSWORD}${SALT}" | openssl dgst -binary -sha1 | xxd -p | sed "s/$/$(echo -n ${SALT} | xxd -p)/" | xxd -r -p | base64)
echo "$NAME:{SSHA}$SHA1"
@reyder
Copy link

reyder commented Feb 17, 2017

Script will fail when you type password with "%" because of printf. Escape it or use echo instead.

@ckujau
Copy link
Author

ckujau commented Nov 22, 2020

Good catch, @reyder! I've adjusted the script. It's using bash anyway, so I guess it's OK the use some bashisms here. Also, someone should tell the Nginx documentation about this ;-)

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