您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

就个人而言,我喜欢使用,sha1(microtime(true).mt_rand(10000,90000))但是您正在寻找更多的可定制方法,因此请尝试使用此功能

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

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

看来你先来了,对不起。:D

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

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 2022/1/1 18:14:32 有535人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶