在 PHP 中生成一次性令牌:random_bytes 或 openssl_random_pseudo_bytes?

Generate a single use token in PHP: random_bytes or openssl_random_pseudo_bytes?

我需要在 PHP 中生成一次性令牌。我可以使用两个似乎做同样事情的函数:random_bytes and openssl_random_pseudo_bytes。例如,使用 random_bytes:

var_dump(bin2hex(random_bytes(12)));

--> string(24) "338f489ec37a2c2b4943905d"

并使用 openssl_random_pseudo_bytes:

var_dump(bin2hex(openssl_random_pseudo_bytes(12)));

--> string(24) "1c7febea20029bd524fba8e7"

openssl_random_pseudo_bytes 是 PHP 5.3 及更高版本(所以我认为它的存在时间更长),random_bytes 是 PHP 7。我正在使用 PHP 7 所以我可以使用任何一个。

那么两者之间有什么主要(或次要)区别吗?如果不是,我很想使用 random_bytes,因为它有一个更简单的名称(= 更易于阅读的代码)。

根据php手册

random_bytes :生成加密安全伪随机字节 openssl_random_pseudo_bytes :生成一个伪随机字节串

所以主要区别在于加密安全

The openssl_random_pseudo_bytes() PHP function calls the RAND_psuedo_bytes() OpenSSL function, which the OpenSSL docs say should only be used for non-cryptographic purposes:

https://paragonie.com/blog/2015/07/how-safely-generate-random-strings-and-integers-in-php

openssl_random_pseudo_bytes是OpenSSL扩展的一部分,必须在PHP编译过程中显式configured and included,需要外部依赖。

random_bytes 是 PHP 7 中的新功能,作为生成随机字节的本机始终可用的 PHP 方法,它根据所处的平台选择其内部随机源。

引入random_bytes的主要原因是在PHP中生成伪随机数据总是让人头疼,需要开发人员具有平台意识并且可能使用几种不同的回退方法取决于可用的扩展或系统级功能。这通常会导致个别实现中出现错误,尤其是在与安全相关的代码中。 random_bytes 通过提供一个始终可用的函数并使用可用的最佳随机源来简化此操作。如果您可以专门针对 PHP 7+,那应该是您的首选方法。

更新一下,openssl_random_pseudo_bytes 中的加密不安全问题已于 2016 年修复。更多详细信息请点击此处:

http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-8867

它现在使用 RAND_bytes,OpenSSL 在其 wiki 中推荐:

https://wiki.openssl.org/index.php/Random_Numbers#FIPS_Mode