且构网

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

在 PHP 中安全的随机数生成

更新时间:2023-09-29 15:57:52

您也可以考虑使用 OpenSSL openssl_random_pseudo_bytes,它从 PHP 5.3 开始可用.

 string openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ] )

生成一串伪随机字节,字节数由长度参数决定.它还指示是否使用加密强算法来生成伪随机字节,并通过可选的 crypto_strong 参数执行此操作.这是 FALSE 的情况很少见,但某些系统可能已损坏或陈旧.

http://www.php.net/手册/en/function.openssl-random-pseudo-bytes.php

从 PHP 7 开始,还有 random_bytes 函数可用

string random_bytes ( int $length )

http://php.net/manual/en/function.random-字节.php

Use case: the "I forgot my password" button. We can't find the user's original password because it's stored in hashed form, so the only thing to do is generate a new random password and e-mail it to him. This requires cryptographically unpredictable random numbers, for which mt_rand is not good enough, and in general we can't assume a hosting service will provide access to the operating system to install a cryptographic random number module etc. so I'm looking for a way to generate secure random numbers in PHP itself.

The solution I've come up with so far involves storing an initial seed, then for each call,

result = seed
seed = sha512(seed . mt_rand())

This is based on the security of the sha512 hash function (the mt_rand call is just to make life a little more difficult for an adversary who obtains a copy of the database).

Am I missing something, or are there better known solutions?

You can also consider using OpenSSL openssl_random_pseudo_bytes, it's available since PHP 5.3.

 string openssl_random_pseudo_bytes ( int $length [, bool &$crypto_strong ] )

Generates a string of pseudo-random bytes, with the number of bytes determined by the length parameter. It also indicates if a cryptographically strong algorithm was used to produce the pseudo-random bytes, and does this via the optional crypto_strong parameter. It's rare for this to be FALSE, but some systems may be broken or old.

http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php

Since PHP 7 there is also random_bytes function available

string random_bytes ( int $length )

http://php.net/manual/en/function.random-bytes.php