PHP生成随机密码
我编写了这个小脚本,它使用一个单词列表来生成一个可读的密码 代码的第一部分通过生成单词和数字来工作。问题在于结尾的符号似乎只是偶尔起作用PHP生成随机密码,php,Php,我编写了这个小脚本,它使用一个单词列表来生成一个可读的密码 代码的第一部分通过生成单词和数字来工作。问题在于结尾的符号似乎只是偶尔起作用 <?php function random_readable_pwd($length=10){ // the wordlist from which the password gets generated // (change them as you like) $words = 'AbbyMallard,AbigailGa
<?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 = "!@#$%^&*()-+?";
$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>
密码生成器
密码生成器
您似乎得到了一个介于0和51之间的随机数,但$syms字符串中只有13个字符。应该是:
$syms = "!@#$%^&*()-+?";
$int = rand(0,12);
$rand_char = $syms[$int];
我还没有测试过,但我认为这就是问题所在
或者更好的是,获得:
提示:将
rand()
替换为mt\u rand()
。第一种是已知的产生极低随机性的方法。mt_rand()
对于加密使用来说也是一种糟糕的选择。改用openssl\u random\u pseudo\u bytes()
。请参阅OpenSSL上的注释,对于加密使用来说,它通常也是一个糟糕的选择。相反,如果您使用的是PHP7+,请使用random\u bytes
或random\u int
。
$syms = "!@#$%^&*()-+?";
$int = rand(0,strlen($syms)-1);
$rand_char = $syms[$int];