【发布时间】:2010-09-07 13:59:39
【问题描述】:
是否有一种编程方式来构建 htpasswd 文件,而不依赖于操作系统特定的功能(即exec()、passthru())?
【问题讨论】:
标签: php automation .htpasswd
是否有一种编程方式来构建 htpasswd 文件,而不依赖于操作系统特定的功能(即exec()、passthru())?
【问题讨论】:
标签: php automation .htpasswd
.httpasswd 文件只是具有特定格式的文本文件,具体格式取决于指定的哈希函数。如果您使用的是 MD5,它们看起来像这样:
foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241
这是登录名、冒号、,$apr1$、salt 和 1000 次 md5 编码为 base64。如果您选择 SHA1,它们看起来像这样:
foo:{SHA}BW6v589SIg3i3zaEW47RcMZ+I+M=
这是登录名、冒号、字符串 {SHA} 和用 base64 编码的 SHA1 哈希。
如果您的语言有 MD5 或 SHA1 和 base64 的实现,您可以像这样创建文件:
<?php
$login = 'foo';
$pass = 'pass';
$hash = base64_encode(sha1($pass, true));
$contents = $login . ':{SHA}' . $hash;
file_put_contents('.htpasswd', $contents);
?>
以下是有关格式的更多信息:
http://httpd.apache.org/docs/2.2/misc/password_encryptions.html
【讨论】:
根据 PHP 网站上的说法,您可以通过以下方法使用 crypt():
<?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);
?>
这个例子的一部分可以找到:http://ca3.php.net/crypt
这当然会覆盖整个现有文件,因此您需要进行某种连接。
我不是 100% 确定这会奏效,但我很确定。
【讨论】:
Trac 附带了一个 Python 替代 htpasswd,我相信您可以将其移植到您选择的语言:htpasswd.py。
【讨论】: