php – 密码安全的唯一ID

我想使用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().

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...