How can I generate a GUID for a string?
I am having a problem generating a GUID for a string - for example:
Guid g = New Guid("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:
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.
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);
}
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.
Here is a list of the most popular hash functions that produce a digest of 128bit:
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:
Today (Aug 2013) the 160bit SHA1 hash can be considered being a good choice.
I'm fairly sure you've confused System.Guid
with wanting a hash (say, SHA-256) of a given string.
Note that, when selecting a cryptographically-secure hashing algorithm, MD5, SHA0 and SHA1 are all generally considered dead. SHA2 and up are still usable.
What you are looking for is probably generating version 3 or version 5 UUIDs, which are name based UUIDs. (version 5 is the recommended). I don't think that the .NET framework has build in support for it. See http://en.wikipedia.org/wiki/Universally_Unique_Identifier
I did a few google searches to see if I could find something in the Win32 API, but nothing came up. However, I am sure that the .NET framework has some implementation hidden somewhere, because as far as I know, when generating a COM object in .NET, and you don't supply an explicit GUID, then the .NET framework generates a name based UUID to create a well-defined ClassID and InterfaceID, ie UUIDs that don't change every time you recompile (like VB6). But this is probably hidden, so I guess you need to implement the algorithm yourself. Luckily, .NET provides both an MD5 and SHA1 algorithm so I don't think implementing a version3 and version5 UUID should be too difficult.
链接地址: http://www.djcxy.com/p/91434.html上一篇: 如何生成新的GUID?
下一篇: 我怎样才能为一个字符串生成一个GUID?