38

Is there a way, from the command line, to check a user and password against a file created by htpasswd, the tool provided by Apache?

Charles
  • 50,943
  • 13
  • 104
  • 142
Pablo Fernandez
  • 279,434
  • 135
  • 377
  • 622
  • Hmm. There's a [tag:htpasswd] tag for questions about the `htpasswd` program, but the system won't let it coexist with the [tag:.htpasswd] tag... – Charles Jun 11 '14 at 06:21
  • 3
    You still haven't accepted the answer. Shame on you. – qwerty_so Nov 28 '19 at 10:21

2 Answers2

50

You can use the htpasswd tool for this.

# create htpasswd_file with user:password
$ htpasswd -cb htpasswd_file user password
Adding password for user user

# verify password for user
$ htpasswd -vb htpasswd_file user wrongpassword
password verification failed

$ htpasswd -vb htpasswd_file user password
Password for user user correct.

Exit status is 0 for success, 3 for failure.

Eren Güven
  • 2,314
  • 19
  • 27
  • 9
    It's generally more secure to omit `-b` and type the password into a prompt. Using the above command, the plaintext password may end up in your `.bash_history`. – Ben Mares Aug 07 '20 at 15:15
42

Assuming you create the password using the following command and "myPassword" as the password

htpasswd -c /usr/local/apache/passwd/passwords username

This will create a file that looks like

username:$apr1$sr15veBe$cwxJZHTVLHBkZKUoTHV.k.

The $apr1$ is the hashing method, sr15veBe is the salt, and the last string is the hashed password. You can validate it using openssl using

openssl passwd -apr1 -salt sr15veBe myPassword

which will output

$apr1$sr15veBe$cwxJZHTVLHBkZKUoTHV.k.

A pipeline which you could use would be:

username="something"
htpasswd -c /usr/local/apache/passwd/passwords $username
****Enter password:****

salt=$($(cat passwords | cut -d$ -f3)
password=$(openssl passwd -apr1 -salt $salt)
****Enter password:****

grep -q $username:$password passwords 
if [ $? -eq 0 ]
 then echo "password is valid"
else 
 echo "password is invalid"
fi

You may need to change your openssl command, as Apache's htpasswd command crypts slightly differently on each system.

For more information, visit Apache's page on the topic at http://httpd.apache.org/docs/2.2/misc/password_encryptions.html

Jonathan Wheeler
  • 2,539
  • 1
  • 19
  • 29