php – 密码安全的唯一ID

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 密码安全的唯一ID脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用PHP生成加密安全的独特的uuids.

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

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

好的,这很容易做到.

什么让你认为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 – 密码安全的唯一ID全部内容,希望文章能够帮你解决php – 密码安全的唯一ID所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。