50

I created a protection for my web pages with apache2 in ubuntu. Now I am creating an application in c++ and I want it uses the same file that Apache2 uses for authentification, but my problem is that I don't know how to decrypt the password generated by apache2. (Maybe I need a key that is used for encryption).

Thank you.

Mils
  • 1,479
  • 3
  • 19
  • 42

2 Answers2

77

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

Sani Huttunen
  • 23,620
  • 6
  • 72
  • 79
  • I Understand. But what he does apache2 when I authenticate in the webpage ? – Mils Nov 11 '12 at 03:12
  • 3
    @Mils: It hashes the password you submit and compares the hash values. – Kerrek SB Nov 11 '12 at 03:13
  • 4
    Apache takes the password provided, hashes it and compares the username provided and the generated hash to the username (if it exists) entry in the .htpasswd file. If they match the user is allowed. – Sani Huttunen Nov 11 '12 at 03:13
  • Then can I do the same thing in C++ ? – Mils Nov 11 '12 at 03:21
  • 4
    Yes you can. You need to know which hash algorithm is used. There are 4 possibilities: Crypt (ALG_CRYPT), MD5 (ALG_APMD5), SHA-1 (ALG_APSHA) and PLAIN TEXT (ALG_PLAIN) (not recmmended). – Sani Huttunen Nov 11 '12 at 03:21
  • 1
    Hey there, I tried to use the both algorithm; Crypt and MD5 But I have a problem when I compare the two passwords, with my code I obtain all time the same password (crypted). I noticed that for the same password if you repeat the process Apache2 generate another encrypted password. – Mils Nov 12 '12 at 15:24
  • 1
    Example : user = "user" and password="password" , apache2 generate this line : " user:$apr1$aYXnafBT$DB49uRgE1cE6e.KY6/SvH0 " with encrypt algorythm and in my program my password encrypted is : "$a5ce6Ndo8z4M". And if I try to generate the same user and password with apache2 I have this line : "user:$apr1$55KyuV1e$z6Ua9BuDqsc338K8.Rfud. " What should I do in comparison ? – Mils Nov 12 '12 at 15:30
  • You write `encrypt algorithm`. You should use a `hash algorithm`. By the looks of the generated password MD5 should be the correct algorithm. – Sani Huttunen Nov 12 '12 at 18:15
  • 4
    Apache uses a salt in the MD5 algorithm. The salt in this case is `$apr1$aYXnafBT` as seen in the generated hash. If you take the salt from the entries and apply it to the password and the generate the hash in c++ you should get the same hash. – Sani Huttunen Nov 12 '12 at 18:23
7

See in particular Apache HTTPd Password Formats

David Tonhofer
  • 14,559
  • 5
  • 55
  • 51