2011-11-29 4 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

팁 :

또는 더 나은의 string's length를 얻을 수()에는, mt_rand'와'랜드를()'대신'. 첫 번째는 극도로 불규칙한 임의성을 생성하는 것으로 알려져 있습니다. –

+0

'mt_rand()'도 암호화 용도로 적합하지 않습니다. 대신'openssl_random_pseudo_bytes()'를 사용하십시오. http://us2.php.net/manual/en/function.mt-rand.php#refsect1-function.mt-randnnotes에서 메모를 참조하십시오. –

답변

6

0에서 51 사이의 임의의 숫자가 표시되지만 $ syms 문자열에는 13 자 밖에 없습니다. 다음과 같아야합니다.

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

테스트하지 않았지만 이것이 문제라고 생각합니다.

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