22

Is there a programmatic way to build htpasswd files, without depending on OS specific functions (i.e. exec(), passthru())?

Cœur
  • 37,241
  • 25
  • 195
  • 267
UnkwnTech
  • 88,102
  • 65
  • 184
  • 229

3 Answers3

38

.httpasswd files are just text files with a specific format depending on the hash function specified. If you are using MD5 they look like this:

foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241

That's the login, a colon, ,$apr1$, the salt and 1000 times md5 encoded as base64. If you select SHA1 they look like this:

foo:{SHA}BW6v589SIg3i3zaEW47RcMZ+I+M=

That's the login, a colon, the string {SHA} and the SHA1 hash encoded with base64.

If your language has an implementation of either MD5 or SHA1 and base64 you can just create the file like this:

<?php

$login = 'foo';
$pass = 'pass';
$hash = base64_encode(sha1($pass, true));

$contents = $login . ':{SHA}' . $hash;

file_put_contents('.htpasswd', $contents);

?>

Here's more information on the format:

http://httpd.apache.org/docs/2.2/misc/password_encryptions.html

federico-t
  • 12,014
  • 19
  • 67
  • 111
Greg Roberts
  • 798
  • 9
  • 14
  • 5
    I found the code to generate the MD5 format password too http://techtalk.virendrachandak.com/using-php-create-passwords-for-htpasswd-file/ –  Mar 03 '14 at 21:55
-1

From what it says on the PHP website, you can use crypt() in the following method:

<?php

// Set the password & username
$username = 'user';
$password = 'mypassword';

// Get the hash, letting the salt be automatically generated
$hash = crypt($password);

// write to a file
file_set_contents('.htpasswd', $username ':' . $contents);

?>

Part of this example can be found: http://ca3.php.net/crypt

This will of course overwrite the entire existing file, so you'll want to do some kind of concatination.

I'm not 100% sure this will work, but I'm pretty sure.

Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
  • crypt format hashing in htpasswd files is obsolete and should not be used. The current default is the md5 variant. – bitmusher Mar 07 '14 at 17:12
-2

Trac ships with a Python replacement for htpasswd, which I'm sure you could port to your language of choice: htpasswd.py.

Jordi Bunster
  • 4,886
  • 3
  • 28
  • 22
  • that imports the crypt module and that is implemented in c –  Jan 24 '09 at 15:52
  • 2
    This solution uses the "crypt" format, one of a handful of options for htpasswd. It is obsolete and should not be used. – bitmusher Mar 07 '14 at 17:11