0

我正在研究 Yii。我想生成 20 位随机密钥。我写了一个函数 -

public function GenerateKey()
{
    //for generating random confirm key
     $length = 20;
     $chars = array_merge(range(0,9), range('a','z'), range('A','Z'));
     shuffle($chars);
     $password = implode(array_slice($chars, 0, $length));
     return $password;
}

此功能正确生成 20 位密钥。但我想要像
“g12a-Gh45-gjk7-nbj8-lhk8”这样的格式的密钥。即用hypen分隔。那么我需要做哪些改变呢?

4

2 回答 2

0

你可以使用这个 Yii 内部函数:

Yii::app()->getSecurityManager()->generateRandomString($length);
于 2014-03-21T10:56:18.793 回答
0

You can use chunk_split() to add the hyphens. substr() is used to remove the trailing hyphen it adds, leaving only those hyphens that actually separate groups.

return substr(chunk_split($password, 4, '-'), 0, 24);

However, note that shuffle() not only uses a relatively poor PRNG but also will not allow the same character to be used twice. Instead, use mt_rand() in a for loop, and then using chunk_split() is easy to avoid:

$password = '';
for ($i = 0; $i < $length; $i++) {
    if ( $i != 0 && $i % 4 == 0 ) { // nonzero and divisible by 4
        $password .= '-';
    }
    $password .= $chars[mt_rand(0, count($chars) - 1)];
}
return $password;

(Even mt_rand() is not a cryptographically secure PRNG. If you need to generate something that must be extremely hard to predict (e.g. an encryption key or password reset token), use openssl_random_pseudo_bytes() to generate bytes and then a separate function such as bin2hex() to encode them into printable characters. I am not familiar with Yii, so I cannot say whether or not it has a function for this.)

于 2013-01-03T09:54:33.257 回答