htpasswd encryption

htpasswd encryption

I was wondering how crypt does the encryption of passwords. Once I needed to compare two .htpasswd files, I was quite sure that both had the same password for the same user, but the encrypted strings didn’t match. I tried to regenerate the encrypted string several times, and here’s what I got :

$ htpasswd -nb someuser somepwd
$ htpasswd -nb someuser somepwd
$ htpasswd -nb someuser somepwd
$ htpasswd -nb someuser somepwd
$ htpasswd -nb someuser somepwd

So, how does it work? How is it possible to compare a password with its encrypted version when you can’t be sure to have the same encryption string each time you encrypt it?
I googled and found that it has something to do with the “salt”. the salt seems to be the 2 first letters of the string, and the password is generated considering those. To be sure, I generated the same password enough times to see :

for i in `seq 1000`; do htpasswd -nb someuser somepwd >> htpasswdtest; done;
sort htpasswdtest

After looking closely to the sorted file, I can say that every time the first 2 letters are identical, the second part of the encrypted string is also identical.

To try to generate a password with a specified salt, you can use the perl crypt function :

perl -le 'print crypt("somepwd", "qQ")'

And then you can see that this comand outputs exactly the same string as the htpasswd had generated above !
Mystery solved ! 😉

Comments are closed.