如何在提供功能的C#中以名称空间和名称作为字符串(根据RFC4122,您需要提供名称空间作为GUID和名称作为字符串)在C#中生成确定性GUID / UUID v3 / v5,所以我想提供两个字符串取而代之的是名称空间的guid和名称的字符串,名称空间的字符串和名称的字符串始终具有相同的GUID / UUID。使用MD5 / SHA1对namespace字符串进行哈希处理并通过Guid(byte [])构造函数使新Guid是完成此操作的安全方法,因此我可以进一步将其提供给函数吗?我不是在问Guid.TryParse()将类似guid-a的字符串解析为名称空间,而是将任何字符串转换为guid命名空间以进一步为以下功能提供它,但是也具有确定性。根据https://github.com/Faithlife/FaithlifeUtility/blob/master/src/Faithlife.Utility/GuidUtility.cs和RFC 4122给定GUID命名空间和字符串名称/任何字符串,这就是创建GUID的方法。
/// <summary>
/// Creates a name-based UUID using the algorithm from RFC 4122 §4.3.
/// </summary>
/// <param name="namespaceId">The ID of the namespace.</param>
/// <param name="nameBytes">The name (within that namespace).</param>
/// <param name="version">The version number of the UUID to create; this value must be either
/// 3 (for MD5 hashing) or 5 (for SHA-1 hashing).</param>
/// <returns>A UUID derived from the namespace and name.</returns>
public static Guid Create(Guid namespaceId, byte[] nameBytes, int version)
{
if (version != 3 && version != 5)
throw new ArgumentOutOfRangeException(nameof(version), "version must be either 3 or 5.");
// convert the namespace UUID to network order (step 3)
byte[] namespaceBytes = namespaceId.ToByteArray();
SwapByteOrder(namespaceBytes);
// compute the hash of the namespace ID concatenated with the name (step 4)
byte[] data = namespaceBytes.Concat(nameBytes).ToArray();
byte[] hash;
using (var algorithm = version == 3 ? (HashAlgorithm) MD5.Create() : SHA1.Create())
hash = algorithm.ComputeHash(data);
// most bytes from the hash are copied straight to the bytes of the new GUID (steps 5-7, 9, 11-12)
byte[] newGuid = new byte[16];
Array.Copy(hash, 0, newGuid, 0, 16);
// set the four most significant bits (bits 12 through 15) of the time_hi_and_version field to the appropriate 4-bit version number from Section 4.1.3 (step 8)
newGuid[6] = (byte) ((newGuid[6] & 0x0F) | (version << 4));
// set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively (step 10)
newGuid[8] = (byte) ((newGuid[8] & 0x3F) | 0x80);
// convert the resulting UUID to local byte order (step 13)
SwapByteOrder(newGuid);
return new Guid(newGuid);
}
BUMP ...
如何在提供功能的C#中以名称空间和名称作为字符串的方式生成确定性GUID / UUID v3 / v5(根据RFC4122,您需要提供名称空间以GUID和名称作为字符串的功能,...
一种方便(有效)的方法是分层名称空间。首先,使用标准DNS名称空间UUID加上您的域名来生成您的根名称空间: