javascript生成的uuid的独特性和随机性如何? [英] How unique and random are javascript generated uuids?

查看:237
本文介绍了javascript生成的uuid的独特性和随机性如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用,因为它使用window.crypto(如果可用).

I'm considering generating unique identifiers for data in javascript using one of the uuid methods discussed here. Most likely something along the lines of this one since it uses window.crypto if it's available.

这些ID不必是全局唯一的,只需每个用户唯一.这会为大型应用程序生成足够唯一的ID吗?是否有任何理由认为这会导致id冲突? javascript可以生成足够随机的uuid来使其正常工作吗?看起来window.crypto相当普及,并且这个特定项目已经需要相当现代的浏览器.

These id's don't need to be globally unique, only unique per user. Will this generate sufficiently unique ids for a large scale application? Is there any reason to think this will result in id collisions? Can javascript generate a sufficiently random uuid for this to work? It looks like window.crypto is fairly widely available and this particular project already requires reasonably modern browsers.

更多信息:有关该问题的一些背景信息可以找到

MORE INFO: some background about the problem can be found here

推荐答案

摘录自此答案的评论:

From the comments on this answer:

...(续)此函数碰撞产生的两个ID的几率 从字面上看,天文数字很小. 128位中除6位外的所有位 ID是随机生成的,这意味着对于任何两个ID,都有一个 在2 ^^ 122(或5.3x10 ^^ 36)中有1个发生碰撞的机会. –丝瓜

... (cont'd) The odds of two IDs generated by this function colliding are, literally, astronomically small. All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide. – broofa

在5,316,911,983,139,663,491,615,228,241,121,378,304(5.3十亿分之一)发生碰撞的机会中,这是十分之一.

That's a 1 in 5,316,911,983,139,663,491,615,228,241,121,378,304 (5.3 undecillion) chance of collision.

还请确保验证,当用户尝试使用此uuid创建新记录时,该uuid尚未使用.这属于不信任用户输入的更大策略.

Also make sure to validate that when a user attempts to create a new record with this uuid, that the uuid is not already in use. This falls under the larger strategy of never trusting user input.

如果您不确定,也可以测试此生成器:

You can also test this generator if you aren't convinced:

function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
  });
}

var uuids = [];
var last;
var numGenerated = 0;
do {
  last = getUUID();
  if (uuids.indexOf(last) === -1) {
    uuids.push(last);
    numGenerated++;
    console.log(numGenerated);
  } else {
    break;
  }
} while (true);

console.log('Got collision after ' + numGenerated + ' generated UUIDS.');

我现在正在Node.js(V8)中运行它,并且在经过170,000个ID之后仍然没有碰撞. 240,000.

I'm running it in Node.js (V8) right now and am still collision-free after 170,000 ids. 240,000.

这篇关于javascript生成的uuid的独特性和随机性如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆