且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 PHP 中生成随机密钥的***方法是什么?

更新时间:2023-09-01 22:44:34

更新 (12/2015):对于 PHP 7.0,您应该使用 random_int() 而不是 mt_rand,因为它提供加密安全值"

Update (12/2015): For PHP 7.0, you should use random_int() instead of mt_rand as it provides "cryptographically secure values"

就个人而言,我喜欢使用 sha1(microtime(true).mt_rand(10000,90000)) 但您正在寻找更多可定制的方法,所以试试这个功能(这是一个修改您对这个答案的要求:

Personally, I like to use sha1(microtime(true).mt_rand(10000,90000)) but you are looking for more of a customizable approach, so try this function (which is a modification to your request of this answer):

function rand_char($length) {
  $random = '';
  for ($i = 0; $i < $length; $i++) {
    $random .= chr(mt_rand(33, 126));
  }
  return $random;
}

不过,这可能会比 uniqid()、md5() 或 sha1() 慢得多.

Still, this will probably be significantly slower than uniqid(), md5(), or sha1().

抱歉,您似乎是第一个知道的.:D

Looks like you got to it first, sorry. :D

编辑 2:我决定用 PHP 5 和 eAccelerator 在我的 Debian 机器上做一个不错的小测试(原谅长代码):

Edit 2: I decided to do a nice little test on my Debian machine with PHP 5 and eAccelerator (excuse the long code):

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:	".(microtime(true) - $a)."
";

$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
  $temp = rand_sha1(1000);

echo "SHA-1:	".(microtime(true) - $a)."
";

$a = microtime(true);
for ($x = 0; $x < 1000; $x++)
  $temp = rand_md5(1000);

echo "MD5:	".(microtime(true) - $a)."
";

结果:

Rand:   2.09621596336
SHA-1:  0.611464977264
MD5:    0.618473052979

所以我的建议是,如果您想要速度(但不是完整字符集),请坚持使用 MD5、SHA-1 或 Uniqid(我还没有测试......)

So my suggestion, if you want speed (but not full charset), is to stick to MD5, SHA-1, or Uniqid (which I didn't test.. yet)