我在用着this https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callbackuuid 的长度为 20。如果生成的 uuid 用于持久唯一值,通常的做法是不检查生成的 uuid 是否尚未使用?
或者,如果必须保持唯一性,最好的做法是验证它尚未被应用程序的某些部分使用。
您可以使用以下方法计算碰撞概率这个公式来自维基百科: https://en.wikipedia.org/wiki/Birthday_attack:
where n(p; H)是为了找到概率至少为的碰撞而必须选择的最小样本数p, given H可能的输出具有相同的概率。
同一篇文章还提供了可用于计算该值的 Python 源代码:
from math import log1p, sqrt
def birthday(probability_exponent, bits):
probability = 10. ** probability_exponent
outputs = 2. ** bits
return sqrt(2. * outputs * -log1p(-probability))
So if you're generating UUIDs with 20 bytes (160 bits) of random data, how sure can you be that there won't be any collisions? Let's suppose you want there to be a probability of less than one in a quintillion (10–18) that a collision will occur:
>>> birthday(-18,160)
1709679290002018.5
这意味着,在生成大约 1.7 万亿个 UUID(每个 UUID 包含 20 字节的随机数据)后,其中两个 UUID 相同的可能性只有五分之一。
基本上,20字节就足够了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)