UUID与互操作的C#代码 [英] UUID interop with c# code
本文介绍了UUID与互操作的C#代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
CAN C#DONet中生成Java代码相同的UUID?如果又如何? !我想GUID,但没有奏效。
Can c# donet generate same UUID for following java code? if so how? i tried GUID but didn't work!
正文:
String cleartext = "CN=CompanyName;mac=some mac;@host=somehost;email=admin@somedomain.com;issued=01/01/20013;expire=12/12/2013";
Java代码:
Java code:
UUID uuid = UUID.nameUUIDFromBytes(cleartext.getBytes("UTF-8"));
C#代码:
C# code:
byte[] b = System.Text.Encoding.UTF8.GetBytes(cleartext);
Guid uid = new Guid(b);
Console.Write(uid.ToString());
REF
的早些时候讨论
推荐答案
如果你需要的是相同的UUID字符串(而不是实际的UUID /的Guid对象),这个C#方法将返回相同的值作为Java的 UUID.nameUUIDFromBytes(字节[])
方法
If all you need is the same UUID string (and not actual UUID/Guid objects), this C# method will return the same value as Java's UUID.nameUUIDFromBytes(byte[])
method.
public static string NameUUIDFromBytes(byte[] input)
{
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(input);
hash[6] &= 0x0f;
hash[6] |= 0x30;
hash[8] &= 0x3f;
hash[8] |= 0x80;
string hex = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
return hex.Insert(8, "-").Insert(13, "-").Insert(18, "-").Insert(23, "-");
}
C#示例
C# Example
string test = "test";
Console.Out.WriteLine(NameUUIDFromBytes(Encoding.UTF8.GetBytes(test)));
Output:
098f6bcd-4621-3373-8ade-4e832627b4f6
Java示例
UUID test = UUID.nameUUIDFromBytes("test".getBytes("UTF-8"));
System.out.println(test);
Output:
098f6bcd-4621-3373-8ade-4e832627b4f6
修改:我知道这事后,但是这将产生相同的值实际的Guid
对象。只是柜面任何人想要它。
Edit: I know it's after the fact, but this will produce an actual Guid
object with the same value. Just incase anyone wants it.
public static Guid NameGuidFromBytes(byte[] input)
{
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(input);
hash[6] &= 0x0f;
hash[6] |= 0x30;
hash[8] &= 0x3f;
hash[8] |= 0x80;
byte temp = hash[6];
hash[6] = hash[7];
hash[7] = temp;
temp = hash[4];
hash[4] = hash[5];
hash[5] = temp;
temp = hash[0];
hash[0] = hash[3];
hash[3] = temp;
temp = hash[1];
hash[1] = hash[2];
hash[2] = temp;
return new Guid(hash);
}
这篇关于UUID与互操作的C#代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文