在PHP中生成一次性使用令牌:random_bytes或openssl_random_pseudo_bytes? [英] Generate a single use token in PHP: random_bytes or openssl_random_pseudo_bytes?

查看:189
本文介绍了在PHP中生成一次性使用令牌:random_bytes或openssl_random_pseudo_bytes?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在PHP中生成一次性令牌.我可以使用两个功能来实现相同的功能: random_bytes openssl_random_pseudo_bytes .例如,使用random_bytes:

I need to generate a single-use token in PHP. There are two functions available that I can use for this that seem to do the same thing: random_bytes and openssl_random_pseudo_bytes. For example, using 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是PHP7.我正在使用PHP 7,因此我可以使用其中任何一个.

openssl_random_pseudo_bytes is PHP 5.3 and up (so I assume it's been around longer), and random_bytes is PHP 7. I'm using PHP 7 so I can use either.

那么两者之间是否有主要(或次要)区别?如果没有,我很想使用random_bytes只是因为它具有更简单的名称(=易于阅读的代码).

So is there any major (or minor for that matter) difference between the two? If not, I'm tempted to go with random_bytes simply because it has an easier name ( = code that's easier to read).

推荐答案

openssl_random_pseudo_bytes是OpenSSL扩展的一部分,必须明确地

openssl_random_pseudo_bytes is part of the OpenSSL extension, which must be explicitly configured and included in the PHP compilation process and requires external dependencies.

random_bytes是PHP 7中的新增功能,它是始终可用的原生PHP方法,用于生成随机字节,该方法根据所使用的平台选择内部的随机性来源.

random_bytes is new in PHP 7 as the native always-available PHP method to generate random bytes, which chooses its internal source of randomness depending on the platform it's on.

引入random_bytes的主要原因是,在PHP中生成伪随机数据始终让人有些头疼,要求开发人员具有平台意识,并可能根据不同的扩展或系统级别使用几种不同的后备方法.功能可用.这通常会导致单个实现中的错误,这在与安全性相关的代码中尤为重要. random_bytes通过提供一个始终可用的功能并使用可能的最佳随机性来源来简化此操作.如果您可以专门定位PHP 7+,则应该使用它.

The main reason for introducing random_bytes was that generating pseudo-random data was always a bit of a headache in PHP, requiring developers to be platform-aware and possibly using several different fallback methods depending on which extensions or system-level functions are available. This often led to bugs in individual implementations, which is particularly concerning in security-relevant code. random_bytes simplifies this by providing one function which is always available and uses the best possible source of randomness available. If you can target PHP 7+ exclusively, it should be your go-to method.

这篇关于在PHP中生成一次性使用令牌:random_bytes或openssl_random_pseudo_bytes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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