Java 中将 String 转换为 UUID 的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25637152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easiest way in Java to turn String into UUID
提问by Guy Kobrinsky
How to generate a valid UUID from a String? The String alone is not what I'm looking for. Rather, I'm looking for something like a hash function converting any String to a valid UUID.
如何从字符串生成有效的 UUID?单独的字符串不是我要找的。相反,我正在寻找类似于将任何字符串转换为有效 UUID 的哈希函数之类的东西。
回答by Chris Martin
In the Java core library, there's java.util.UUID.nameUUIDFromBytes(byte[])
.
在 Java 核心库中,有java.util.UUID.nameUUIDFromBytes(byte[])
.
I wouldn't recommend it because it's UUID 3 which is based on MD5, a very broken hash function. You'd be better off finding an implementation of UUID 5, which is based on SHA-1 (better although also sort of broken).
我不会推荐它,因为它是基于 MD5 的 UUID 3,这是一个非常破碎的哈希函数。你最好找到一个基于 SHA-1 的 UUID 5 的实现(更好,虽然也有点坏)。
回答by Raj
Try this out:
试试这个:
String superSecretId = "f000aa01-0451-4000-b000-000000000000";
UUID.fromString(superSecretId);
I am using this in my project and it works. Make sure you import the right stuff.
我在我的项目中使用它并且它有效。确保您导入正确的东西。