以编程方式构建 htpasswd

2022-08-30 19:10:45

有没有一种编程方法来构建htpasswd文件,而不依赖于操作系统特定的功能(即,)?exec()passthru()


答案 1

.httpasswd文件只是具有特定格式的文本文件,具体取决于指定的哈希函数。如果您使用的是 MD5,它们如下所示:

foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241

这是登录名,冒号,$apr 1$,盐和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


答案 2

根据它在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%确定这会起作用,但我非常确定。


推荐