gpt4 book ai didi

php - 加密安全的唯一 ID

转载 作者:行者123 更新时间:2023-12-03 00:11:33 27 4
gpt4 key购买 nike

我想使用 php 生成加密安全的唯一 uuid。

uniqid() 提供唯一但不安全的 id,openssl_random_pseudo_bytes() 提供安全但不唯一的 id。两者的结合(以下代码)是正确的方法还是有更好的解决方案?

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()

关于php - 加密安全的唯一 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31451405/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com