2011-11-29 195 views
2

我已經放在一起這個小腳本,它使用一個單詞列表來生成一個可讀的密碼。PHP生成隨機密碼

代碼的第一部分通過生成單詞和數字而正常工作。問題在於最後的符號似乎每隔一段時間都會有效。

<?php 
function random_readable_pwd($length=10){ 

    // the wordlist from which the password gets generated 
    // (change them as you like) 
    $words = 'AbbyMallard,AbigailGabble,AbisMal,Abu,Adella,TheAgent,AgentWendyPleakley,Akela,AltheAlligator,Aladar,Aladdin,AlamedaSlim,AlanaDale,Alana,Alcmene,Alice,AmeliaGabble,AmosSlade,Amphitryon,AnastasiaTremaine,Anda,Andrina,Angelique,AngusMacBadger'; 

    // Split by ",": 
    $words = explode(',', $words); 
    if (count($words) == 0){ die('Wordlist is empty!'); } 

    // Add words while password is smaller than the given length 
    $pwd = ''; 
    while (strlen($pwd) < $length){ 
     $r = mt_rand(0, count($words)-1); 
     $pwd .= $words[$r]; 
    } 

    $num = mt_rand(1, 99); 
    if ($length > 2){ 
     $pwd = substr($pwd,0,$length-strlen($num)).$num; 
    } else { 
     $pwd = substr($pwd, 0, $length); 
    } 

    $pass_length = strlen($pwd); 
    $random_position = rand(0,$pass_length); 

    $syms = "[email protected]#$%^&*()-+?"; 
    $int = rand(0,51); 
    $rand_char = $syms[$int]; 

    $pwd = substr_replace($pwd, $rand_char, $random_position, 0); 

    return $pwd; 
} 


?> 
<html><head><title>Password generator</title></head> 
<body> 
<h1>Password generator</h2> 

<p> 
<?php 
echo random_readable_pwd(10); 
?> 
</p> 

</body> 
</html> 
+1

提示:用'mt_rand替換'蘭特()'()'。第一個是知道產生非常差的隨機性。 –

+0

'mt_rand()'在加密使用中也是一個糟糕的選擇。改爲使用'openssl_random_pseudo_bytes()'。請參閱http://us2.php.net/manual/en/function.mt-rand.php#refsect1-function.mt-rand-notes上的說明 –

回答

6

你似乎得到一個介於0和51之間的隨機數,但$ syms字符串中只有13個字符。它應該是:

$syms = "[email protected]#$%^&*()-+?"; 
$int = rand(0,12); 
$rand_char = $syms[$int]; 

沒有測試過這個,但我認爲這是問題所在。

甚至更​​好,得到了string's length

$syms = "[email protected]#$%^&*()-+?"; 
$int = rand(0,strlen($syms)-1); 
$rand_char = $syms[$int];