gpt4 book ai didi

c# - UUID 与 c# 代码互操作

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:13 25 4
gpt4 key购买 nike

c# donet 可以为以下 java 代码生成相同的 UUID 吗?如果是这样怎么办?我试过 GUID 但没有用!

文本:

String cleartext = "CN=CompanyName;mac=some mac;@host=somehost;email=admin@somedomain.com;issued=01/01/20013;expire=12/12/2013";

Java代码:

UUID uuid = UUID.nameUUIDFromBytes(cleartext.getBytes("UTF-8"));

C#代码:

byte[] b = System.Text.Encoding.UTF8.GetBytes(cleartext);
Guid uid = new Guid(b);
Console.Write(uid.ToString());

引用文献 Earlier discussions

最佳答案

如果您只需要相同的 UUID 字符串(而不是实际的 UUID/Guid 对象),此 C# 方法将返回与 Java 的 UUID.nameUUIDFromBytes(byte[]) 方法相同的值。

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# 示例

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 对象。以防万一有人想要它。

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);
}

关于c# - UUID 与 c# 代码互操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18021808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com