我希望创建一个可重用的函数,该函数将生成一个随 secret 钥,其中包含选定长度的可打印 ACSII 字符(从 2 到 1000+)。我认为可打印的 ASCII 字符是 33-126。它们的 key 不需要完全唯一,只要在完全相同的毫秒内生成即可(因此 uniqid()
不起作用)。
我认为 chr()
和 mt_rand()
的组合可能会起作用。
这是要走的路,还是其他最好的方法?
编辑: uniqid()
也不起作用,因为它没有长度参数,它只是 PHP 给你的。
我的想法:这就是我想出的:
function GenerateKey($length = 16) {
$key = '';
for($i = 0; $i < $length; $i ++) {
$key .= chr(mt_rand(33, 126));
}
return $key;
}
这有什么问题吗?
另一个编辑:其他大多数问题都与密码生成有关。我想要更多种类的字符,我不关心 1
与 l
。我希望尽可能多的可能键。
注意:生成的 key 不一定是加密安全的。
最佳答案
更新 (12/2015):对于 PHP 7.0,您应该使用 random_int()
而不是 mt_rand
因为它提供“加密安全值”
就我个人而言,我喜欢使用 sha1(microtime(true).mt_rand(10000,90000))
但您正在寻找更多可定制的方法,所以试试这个函数(这是一个修改应您的this answer 的要求):
function rand_char($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(mt_rand(33, 126));
}
return $random;
}
不过,这可能会比 uniqid()、md5() 或 sha1() 慢得多。
编辑:看来你先搞定了,抱歉。 :D
编辑 2: 我决定在我的 Debian 机器上用 PHP 5 和 eAccelerator 做一个不错的小测试(请原谅长代码):
function rand_char($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(mt_rand(33, 126));
}
return $random;
}
function rand_sha1($length) {
$max = ceil($length / 40);
$random = '';
for ($i = 0; $i < $max; $i ++) {
$random .= sha1(microtime(true).mt_rand(10000,90000));
}
return substr($random, 0, $length);
}
function rand_md5($length) {
$max = ceil($length / 32);
$random = '';
for ($i = 0; $i < $max; $i ++) {
$random .= md5(microtime(true).mt_rand(10000,90000));
}
return substr($random, 0, $length);
}
$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_char(1000);
echo "Rand:\t".(microtime(true) - $a)."\n";
$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_sha1(1000);
echo "SHA-1:\t".(microtime(true) - $a)."\n";
$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
$temp = rand_md5(1000);
echo "MD5:\t".(microtime(true) - $a)."\n";
结果:
Rand: 2.09621596336
SHA-1: 0.611464977264
MD5: 0.618473052979
所以我的建议是,如果您想要速度(但不是完整的字符集),请坚持使用 MD5、SHA-1 或 Uniqid(我还没有测试......)
关于php - 在 PHP 中生成随 secret 钥的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/637278/