我试图在php中生成一个随机密码。
但是我得到的都是'a'返回类型是数组类型,我希望它是字符串。对如何修改代码有什么想法吗?
谢谢。
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
for ($i = 0; $i < 8; $i++) {
$n = rand(0, count($alphabet)-1);
$pass[$i] = $alphabet[$n];
}
return $pass;
}
TL; diana:
使用random_int()和下面给定的random_str()。
如果没有random_int(),请使用random_compat。
解释:
由于您正在生成密码,因此需要确保所生成的密码是不可预测的,而确保在实现中出现此属性的唯一方法是使用加密安全的伪随机数生成器(CSPRNG)。
对于随机字符串的一般情况,可以放宽对CSPRNG的要求,但在涉及安全性时则不能。
在PHP中,密码生成的简单、安全且正确的答案是使用RandomLib,不要重复工作。这个库已经被行业安全专家和我自己审计过了。
对于喜欢发明自己的解决方案的开发人员,PHP 7.0.0将为此目的提供random_int()。如果你还在使用PHP 5。x,我们为random_int()写了一个PHP 5的polyfill,这样你就可以在PHP 7发布之前使用新的API。使用random_int()填充可能比编写自己的实现更安全。
有了一个安全的随机整数生成器,生成一个安全的随机字符串比饼更容易:
<?php
/**
* Generate a random string, using a cryptographically secure
* pseudorandom number generator (random_int)
*
* For PHP 7, random_int is a PHP core function
* For PHP 5.x, depends on https://github.com/paragonie/random_compat
*
* @param int $length How many characters do we want?
* @param string $keyspace A string of all possible characters
* to select from
* @return string
*/
function random_str(
$length,
$keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
) {
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
if ($max < 1) {
throw new Exception('$keyspace must be at least two characters long');
}
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
我知道您正在尝试以特定的方式生成密码,但您可能也想看看这个方法……
$bytes = openssl_random_pseudo_bytes(2);
$pwd = bin2hex($bytes);
它取自php.net站点,它创建了一个字符串,长度是您在openssl_random_pseudo_bytes函数中输入的数字的两倍。因此,上面的代码将创建一个长度为4个字符的密码。
总之……
$pwd = bin2hex(openssl_random_pseudo_bytes(4));
会创建一个8个字符长的密码。
但是请注意,密码只包含数字0-9和小写字母a-f!
这是我的密码助手
class PasswordHelper
{
/**
* generate a secured random password
*/
public static function generatePassword(
int $lowerCaseCount=8,
int $upperCaseCount=8,
int $numberCount=8,
int $specialCount=4
): string
{
$lowerCase = 'abcdefghijklmnopqrstuvwxyz';
$upperCase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$number = '0123456789';
$special = '!@#$%^&*';
$password = self::getRandom($lowerCase, $lowerCaseCount);
$password .= self::getRandom($upperCase, $upperCaseCount);
$password .= self::getRandom($number, $numberCount);
$password .= self::getRandom($special, $specialCount);
return str_shuffle($password);
}
/**
* get a random string from a set of characters
*/
public static function getRandom($set, $length): string
{
$rand = '';
$setLength = strlen($set);
for ($i = 0; $i < $length; $i++)
{
$rand .= $set[random_int(0, $setLength - 1)];
}
return $rand;
}
}
用法:
PasswordHelper::generatePassword()或PasswordHelper::generatePassword(2,4,5,3)