28

I see quit a few implementations of unique string generation for things like uploaded image names, session IDs, et al, and many of them employ the usage of hashes like SHA1, or others.

I'm not questioning the legitimacy of using custom methods like this, but rather just the reason. If I want a unique string, I just say this:

>>> import uuid
>>> uuid.uuid4()
UUID('07033084-5cfd-4812-90a4-e4d24ffb6e3d')

And I'm done with it. I wasn't very trusting before I read up on uuid, so I did this:

>>> import uuid
>>> s = set()
>>> for i in range(5000000):  # That's 5 million!
>>>     s.add(str(uuid.uuid4()))
...
...
>>> len(s)
5000000

Not one repeater (I wouldn't expect one now considering the odds are like 1.108e+50, but it's comforting to see it in action). You could even half the odds by just making your string by combining 2 uuid4()s.

So, with that said, why do people spend time on random() and other stuff for unique strings, etc? Is there an important security issue or other regarding uuid?

4

6 回答 6

20

使用散列唯一标识资源允许您从对象生成“唯一”引用。例如,Git 使用 SHA 散列来生成一个唯一的散列,该散列代表单个提交的确切变更集。由于散列是确定性的,因此您每次都会为同一个文件获得相同的散列。

世界各地的两个人可以独立地对同一个 repo 进行相同的更改,Git 会知道他们进行了相同的更改。UUID v1、v2 和 v4 不支持,因为它们与文件或文件内容无关。

于 2012-09-10T22:12:33.560 回答
12

好吧,有时你想要碰撞。如果有人两次上传相同的完全相同的图像,也许您宁愿告诉他们这是重复的,而不是用新名称制作另一个副本。

于 2010-03-12T18:38:06.697 回答
6

一个可能的原因是您希望唯一的字符串是人类可读的。UUID 只是不容易阅读。

于 2010-03-12T18:37:43.750 回答
3

uuid 很长且无意义(例如,如果您按 uuid 排序,则会得到无意义的结果)。

而且,因为它太长了,我不想把它放在一个 URL 中或以任何形状或形式将它暴露给用户。

于 2010-03-12T18:41:50.360 回答
1

除了其他答案之外,哈希对于应该是不可变的东西真的很有用。该名称是唯一的,可用于随时检查它所附加的任何内容的完整性。

于 2014-10-24T20:34:15.180 回答
1

另请注意,其他类型的 UUID 甚至可能是合适的。例如,如果您希望您的标识符可订购,则 UUID1 部分基于时间戳。这完全取决于您的应用程序要求......

于 2016-02-01T19:15:43.740 回答