php – 密码安全的唯一ID

前端之家收集整理的这篇文章主要介绍了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().

原文链接:/php/131998.html

猜你在找的PHP相关文章