加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 密码安全的唯一ID

发布时间:2020-12-13 16:40:47 所属栏目:PHP教程 来源:网络整理
导读:我想使用php生成加密安全的独特的uuids. uniqid()提供唯一但不安全的ids,openssl_random_pseudo_bytes()提供安全但不唯一的ids.两者的组合(以下代码)是否适当的方法或者是否有更好的解决方案? uniqid(bin2hex(openssl_random_pseudo_bytes(10)),true); I wa
我想使用php生成加密安全的独特的uuids.

uniqid()提供唯一但不安全的ids,openssl_random_pseudo_bytes()提供安全但不唯一的ids.两者的组合(以下代码)是否适当的方法或者是否有更好的解决方案?

uniqid(bin2hex(openssl_random_pseudo_bytes(10)),true);

I want to generate cryptographically secure unique uuids using php.

好的,这很容易做到.

uniqid() provides unique but not secure ids and openssl_random_pseudo_bytes() provides secure but not unique ids.

什么让你认为cryptographically secure pseudorandom number不是独一无二的?

/**
 * Return a UUID (version 4) using random bytes
 * Note that version 4 follows the format:
 *     xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
 * where y is one of: [8,9,A,B]
 * 
 * We use (random_bytes(1) & 0x0F) | 0x40 to force
 * the first character of hex value to always be 4
 * in the appropriate position.
 * 
 * For 4: http://3v4l.org/q2JN9
 * For Y: http://3v4l.org/EsGSU
 * For the whole shebang: https://3v4l.org/LNgJb
 * 
 * @ref https://stackoverflow.com/a/31460273/2224584
 * @ref https://paragonie.com/b/JvICXzh_jhLyt4y3
 * 
 * @return string
 */
function uuidv4()
{
    return implode('-',[
        bin2hex(random_bytes(4)),bin2hex(random_bytes(2)),bin2hex(chr((ord(random_bytes(1)) & 0x0F) | 0x40)) . bin2hex(random_bytes(1)),bin2hex(chr((ord(random_bytes(1)) & 0x3F) | 0x80)) . bin2hex(random_bytes(1)),bin2hex(random_bytes(6))
    ]);
}

上述示例符合UUIDv4 specification并使用PHP7的random_bytes()功能.

对于PHP 5项目,您可以使用random_compat将来自PHP 7的random_bytes()进行polyfill.或者,您也可以使用openssl_random_pseudo_bytes()代替random_bytes().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读