我试图在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;
}

其他回答

我将发布一个答案,因为现有的一些答案很接近,但有一个:

一个比你想要的更小的字符空间,这样在相同的熵下,强制操作更容易,或者密码必须更长 不被认为是加密安全的RNG 一些第三方库的需求,我认为这可能是有趣的,展示什么可能需要自己做

这个答案将规避计数/strlen问题,因为生成的密码的安全性,至少在我看来,超越了你如何到达那里。我还将假设PHP > 5.3.0。

让我们把这个问题分解成几个组成部分:

使用一些安全的随机来源来获取随机数据 使用该数据并将其表示为一些可打印的字符串

对于第一部分,PHP > 5.3.0提供了函数openssl_random_pseudo_bytes。注意,虽然大多数系统使用加密强算法,但你必须检查,所以我们将使用包装器:

/**
 * @param int $length
 */
function strong_random_bytes($length)
{
    $strong = false; // Flag for whether a strong algorithm was used
    $bytes = openssl_random_pseudo_bytes($length, $strong);

    if ( ! $strong)
    {
        // System did not use a cryptographically strong algorithm 
        throw new Exception('Strong algorithm not available for PRNG.');
    }        

    return $bytes;
}

对于第二部分,我们将使用base64_encode,因为它接受一个字节字符串,并将生成一系列字母非常接近原始问题中指定的字母的字符。如果我们不介意在最后的字符串中出现+,/和=字符,并且我们希望结果至少有$n个字符长,我们可以简单地使用:

base64_encode(strong_random_bytes(intval(ceil($n * 3 / 4))));

The 3/4 factor is due to the fact that base64 encoding results in a string that has a length at least a third bigger than the byte string. The result will be exact for $n being a multiple of 4 and up to 3 characters longer otherwise. Since the extra characters are predominantly the padding character =, if we for some reason had a constraint that the password be an exact length, then we can truncate it to the length we want. This is especially because for a given $n, all passwords would end with the same number of these, so that an attacker who had access to a result password, would have up to 2 less characters to guess.


对于额外的学分,如果我们想要满足OP的问题中的确切规格,那么我们将不得不做更多的工作。在这里我将放弃碱基转换方法,而使用一个快速而肮脏的方法。这两种方法都需要产生比结果中所使用的更多的随机性,因为字母表有62个条目。

对于结果中的额外字符,我们可以简单地将它们从结果字符串中丢弃。如果我们在字节串中开始有8个字节,那么多达25%的base64字符将是这些“不受欢迎的”字符,因此简单地丢弃这些字符将导致不少于OP所需的字符串。然后我们可以简单地截断它以得到准确的长度:

$dirty_pass = base64_encode(strong_random_bytes(8)));
$pass = substr(str_replace(['/', '+', '='], ['', '', ''], $dirty_pass, 0, 8);

如果您生成较长的密码,填充字符=在中间结果中所占的比例会越来越小,这样您就可以实现更精简的方法(如果需要耗尽用于PRNG的熵池)。

这是基于本页的另一个答案,https://stackoverflow.com/a/21498316/525649

这个答案只生成十六进制字符,0-9,a-f。对于一些看起来不像hex的东西,试试这个:

str_shuffle(
  rtrim(
    base64_encode(bin2hex(openssl_random_pseudo_bytes(5))),
    '='
  ). 
  strtoupper(bin2hex(openssl_random_pseudo_bytes(7))).
  bin2hex(openssl_random_pseudo_bytes(13))
)

Base64_encode返回更广泛的字母数字字符 Rtrim有时会在结尾删除=

例子:

32 efvfgdg891be5e7293e54z1d23110m3zu3fmjb30z9a740ej0jz4 b280R72b48eOm77a25YCj093DE5d9549Gc73Jg8TdD9Z0Nj4b98760 051年b33654c0eg201cfw0e6na4b9614ze8d2fn49e12y0zy557aucb8 y67Q86ffd83G0z00M0Z152f7O2ADcY313gD7a774fc5FF069zdb5b7

对于为用户创建界面来说,这不是很可配置的,但对于某些目的来说,这是可以的。增加字符数,以弥补特殊字符的不足。

//define a function. It is only 3 lines!   
function generateRandomPassword($length = 5){
    $chars = "0123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
    return substr(str_shuffle($chars),0,$length);
}

//usage
echo generateRandomPassword(5); //random password legth: 5
echo generateRandomPassword(6); //random password legth: 6
echo generateRandomPassword(7); //random password legth: 7

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;
}

下面是我对随机密码生成助手的看法。

它确保密码包含数字,大写字母和小写字母,以及至少3个特殊字符。

密码长度为11 ~ 30。

function plainPassword(): string
{
    $numbers = array_rand(range(0, 9), rand(3, 9));
    $uppercase = array_rand(array_flip(range('A', 'Z')), rand(2, 8));
    $lowercase = array_rand(array_flip(range('a', 'z')), rand(3, 8));
    $special = array_rand(array_flip(['@', '#', '$', '!', '%', '*', '?', '&']), rand(3, 5));

    $password = array_merge(
        $numbers,
        $uppercase,
        $lowercase,
        $special
    );

    shuffle($password);

    return implode($password);
}