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

这篇博客探讨了在PHP中生成随机字符串的不同方法,包括random_int(), sha1(), 和 md5()。作者推荐使用random_int(),因为它提供加密安全的值。同时,通过性能测试,发现md5()和sha1()在速度上优于rand_char(),但可能不如uniqid()。测试结果显示,MD5最快。如果你需要快速生成字符串,MD5可能是更好的选择。
摘要由CSDN通过智能技术生成

小编典典

更新(12/2015):对于PHP7.0,您应该使用random_int()而不是,mt_rand因为它提供了“加密安全值”

就个人而言,我喜欢使用,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

编辑2: 我决定使用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(我尚未测试过。)

2020-05-29

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值