在php中生成加密安全的随机数 [英] Generate cryptographically secure random numbers in php

查看:474
本文介绍了在php中生成加密安全的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP的rand()函数不能提供良好的随机数.因此,我开始使用mt_rand(),据说效果更好.但是这些结果有多好?有什么方法可以再次改善它们?

我的想法:

function rand_best($min, $max) {
    $generated = array();
    for ($i = 0; $i < 100; $i++) {
        $generated[] = mt_rand($min, $max);
    }
    shuffle($generated);
    $position = mt_rand(0, 99);
    return $generated[$position];
}

这应该给您完美的"随机数,不是吗?

解决方案

伪随机数生成器 (PRNG)是非常复杂的野兽.

没有真正的完美"随机数生成器-实际上,可以用数学函数完成的最好的事情是伪随机数-对于大多数意图和目的,它们看起来都是足够随机的.

实际上,从PRNG返回的数字中执行任何其他操作并不会真正增加其随机性,并且实际上,数字的随机性会降低.

所以,我最好的建议是,不要弄乱从PRNG返回的值.使用足够适合预期用途的PRNG,如果不合适,则在必要时找到可以产生更好效果的PRNG.

坦率地说,看来 mt_rand 函数使用梅森捻线器,它实际上是一个非常好的PRNG,所以可能足以满足大多数休闲用途.

但是, Merenne Twister并非旨在用于任何安全上下文中.有关需要随机性以确保安全性的解决方案,请参见此答案.

修改

注释中有一个问题,为什么对随机数执行运算可以使其随机性降低.例如,某些PRNG可以在比特的不同部分返回更一致,更少的随机数-高端可能比低端更多.

因此,在丢弃高端并返回低端的操作中,该值的随机性可能小于从PRNG返回的原始值.

目前我找不到很好的解释,但是我基于Java文档中的

Pseudorandom number generators (PRNG) are very complex beast.

There are no real "perfect" random number generators -- in fact the best that can be done from mathematical functions are pseudorandom -- they seem random enough for most intents and purposes.

In fact, performing any additional actions from a number returned by a PRNG doesn't really increase its randomness, and in fact, the number can become less random.

So, my best advice is, don't mess around with values returned from a PRNG. Use a PRNG that is good enough for the intended use, and if it isn't, then find a PRNG that can produce better results, if necessary.

And frankly, it appears that the mt_rand function uses the Mersenne twister, which is a pretty good PRNG as it is, so it's probably going to be good enough for most casual use.

However, Mersenne Twister is not designed to be used in any security contexts. See this answer for a solution to use when you need randomness to ensure security.

Edit

There was a question in the comments why performing operations on a random number can make it less random. For example, some PRNGs can return more consistent, less random numbers in different parts of the bits -- the high-end can be more random than the low-end.

Therefore, in operations where the high-end is discarded, and the low end is returned, the value can become less random than the original value returned from the PRNG.

I can't find a good explanation at the moment, but I based that from the Java documentation for the Random.nextInt(int) method, which is designed to create a fairly random value in a specified range. That method takes into account the difference in randomness of the parts of the value, so it can return a better random number compared to more naive implementations such as rand() % range.

这篇关于在php中生成加密安全的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆