2008-09-02 66 views

回答

33

.httpasswd文件只是具有特定格式的文本文件,具體取決於指定的哈希函數。如果您正在使用MD5,就像這樣:

foo:$apr1$y1cXxW5l$3vapv2yyCXaYz8zGoXj241 

這就是登錄,冒號,$ APR1 $,鹽和1000次MD5編碼爲Base64。如果選擇SHA1,就像這樣:

foo:{SHA}BW6v589SIg3i3zaEW47RcMZ+I+M= 

這就是登錄,冒號,字符串{} SHA與base64編碼的SHA1哈希。

如果你的語言有MD5或SHA-1和的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

+4

我發現代碼生成的MD5格式的密碼太http://techtalk.virendrachandak.com/using-php-create-passwords-for-htpasswd-file/ – 2014-03-03 21:55:49

-1

Trac附帶一個Python替代htpasswd,我相信你可以移植到你選擇的語言:htpasswd.py

+0

導入crypt模塊並在c – hop 2009-01-24 15:52:40

+1

中實現該解決方案使用「crypt」格式,這是htpasswd的一些選項之一。它已過時,不應使用。 – bitmusher 2014-03-07 17:11:51

2

首先,創建這種形式:

<FORM METHOD="POST" ACTION="<? echo $_SERVER['PHP_SELF']; ?>" onSubmit='return ValidateForm()'> 
    Username<br /><INPUT TYPE="TEXT" NAME="user[]"><br /><br /> 
    Password<br /><INPUT TYPE="PASSWORD" NAME="password1[]"><br /> 
    <INPUT TYPE="PASSWORD" NAME="password2[]"><br /><br /> 
    <INPUT type=submit name="submit" VALUE="Create .htpasswd entry" onclick="document.all.submit.style.visibility='hidden'"> 
</FORM> 

然後,這個PHP代碼會爲你創建的密碼:

if (isset($_POST['user']) && isset($_POST['password1'])) { 
    if($_POST['password1'] == $_POST['password2']) { 
     $user = $_POST['user']; 
     $password1 = $_POST['password1']; 
     $htpasswd_text = ""; 
     for ($i = 0; $i < count ($user); $i++) { 
      $htpasswd_text .= "$user[$i]:".crypt($password1[$i],CRYPT_STD_DES).""; 
     } 
     echo "<br />Copy this line to your .htpasswd file:"; 
     echo "<pre style=\"border-bottom-width:1px;border-bottom-style:solid;\">"; 
     echo nl2br($htpasswd_text); 
     echo "</pre><br />"; 
    } else { 
     echo "<pre style=\"border-bottom-width:1px;border-bottom-style:solid;\">Passwords do not match !</pre><br />"; 
    } 
} 

的實際文本將追加到您HTPASSWD文件在$htpasswd_text變量。

+0

crypt格式哈希已過時,不應再使用。 htpasswd的當前默認值爲md5。 – bitmusher 2014-03-07 17:13:36

-1

從它在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%肯定這會工作,但我很確定。

相關問題