如何为字符串生成GUID? [英] How can I generate a GUID for a string?

查看:152
本文介绍了如何为字符串生成GUID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在生成字符串的GUID时遇到问题-例如:

I am having a problem generating a GUID for a string - for example:

Guid g = New Guid("Mehar");

如何为 Mehar ?我正在遇到异常。

How can I compute a GUID for "Mehar"? I am getting an exception.

推荐答案

这个线程很旧,但这是我们解决此问题的方法:

Quite old this thread but this is how we solved this problem:

由于.NET框架中的Guid是任意的16个字节或分别为128位,因此您可以通过将任意哈希函数应用于生成16个字节的哈希值的字符串,然后将

Since Guid's from the .NET framework are arbitrary 16bytes, or respectively 128bits, you can calculate a Guid from arbitrary strings by applying any hash function to the string that generates a 16 byte hash and subsequently pass the result into the Guid constructor.

我们决定使用MD5哈希函数,示例代码如下:

We decided to use the MD5 hash function and an example code could look like this:

string input = "asdfasdf";
using (MD5 md5 = MD5.Create())
{
    byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(input));
    Guid result = new Guid(hash);
}

请注意,这一代Guid本身具有一些缺陷,例如这取决于哈希函数的质量!如果您的哈希函数为您使用的许多字符串生成相等的哈希,则会影响软件的行为。

Please note that this Guid generation has a few flaws by itself as it depends on the quality of the hash function! If your hash function generates equal hashes for lots of string you use, it's going to impact the behaviour of your software.

以下是生成128位摘要的最受欢迎的哈希函数列表:

Here is a list of the most popular hash functions that produce a digest of 128bit:


  • RIPEMD(冲突概率:2 ^ 18)

  • MD4(确实发生碰撞的可能性)

  • MD5(发生碰撞的可能性:2 ^ 20.96)

请注意,还可以使用其他产生较大摘要的哈希函数,并仅将其截断。因此,使用更新的哈希函数可能很聪明。列出一些内容:

Please note that one can use also other hash functions that produce larger digests and simply truncate those. Therefore it may be smart to use a newer hash function. To list some:


  • SHA-1

  • SHA-2

  • SHA-3

今天(2013年8月),可以认为160bit SHA1哈希是一个不错的选择。

Today (Aug 2013) the 160bit SHA1 hash can be considered being a good choice.

这篇关于如何为字符串生成GUID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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