Ner*_*ere 5 php security random passwords
我需要生成带有以下条件的随机密码:
我尝试过的代码:
function generateRandomPassword() {
//Initialize the random password
$password = '';
//Initialize a random desired length
$desired_length = rand(8, 12);
for($length = 0; $length < $desired_length; $length++) {
//Append a random ASCII character (including symbols)
$password .= chr(rand(32, 126));
}
return $password;
}
Run Code Online (Sandbox Code Playgroud)
如何避免这4个字符=>“ l1o0 ”?
原因:
谢谢!
请不要使用当前提供的用于生成密码的其他任何答案。他们无论如何都不安全。
rand()
->没有mt_rand()
->绝对不是我将从博客文章“ 如何在PHP中安全地生成随机字符串和整数”中提出该解决方案。
/**
* Note: See https://paragonie.com/b/JvICXzh_jhLyt4y3 for an alternative implementation
*/
function random_string($length = 26, $alphabet = 'abcdefghijklmnopqrstuvwxyz234567')
{
if ($length < 1) {
throw new InvalidArgumentException('Length must be a positive integer');
}
$str = '';
$alphamax = strlen($alphabet) - 1;
if ($alphamax < 1) {
throw new InvalidArgumentException('Invalid alphabet');
}
for ($i = 0; $i < $length; ++$i) {
$str .= $alphabet[random_int(0, $alphamax)];
}
return $str;
}
Run Code Online (Sandbox Code Playgroud)
用法:
// Every ASCII alphanumeric except "loIO01":
$alphabet = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$string = random_string(12, $alphabet);
Run Code Online (Sandbox Code Playgroud)
您可能没有random_int()
,除非您在以后发布PHP 7时阅读此内容。对于生活在当下的我们来说,请使用random_compat。