GUID的长度必须为16字节
本文关键字:16字节 GUID | 更新日期: 2023-09-27 18:29:39
我试图用另一个以字符串为参数的方法重载一个使用Guid作为参数的方法。
// read a student object from the dictionary
static public User Retrieve(Guid ID)
{
User user;
// find the Guid in the Dictionary
user = Users[ID];
return user;
}
static public User Retrieve(string Email)
{
User user;
Guid id;
// find the Guid in the Dictionary
using (SHA1 sha1 = SHA1.Create())
{
byte[] hash = SHA1.ComputeHash(Encoding.Default.GetBytes(Email));
id = new Guid(hash);
}
user = Users[id];
return user;
}
测试结果结果消息:测试方法SRS.CRUDUsers.UpdateStudent引发异常:System.ArgumentException:GUID的字节数组长度必须恰好为16字节。
测试方法:
public void UpdateStudent()
{
// Arrange
Student expected = (Student)UserRepo.Retrieve("info@info.com");
// Act
Student actual = (Student)UserRepo.Retrieve("info@info.com");
actual.FirstName = "Joe";
actual.LastName = "Brown";
actual.Birthday = new DateTime(1977, 2, 23);
actual.DegreeSelected = 1;
// Assert (this is only really checking the object agains itself
// because both variables are referencing the same object).
Assert.IsNotNull(actual.ID);
Console.WriteLine(actual.ID);
Assert.AreEqual(expected.Name, actual.Name);
Assert.AreEqual(expected.GetType(), actual.GetType());
Assert.AreEqual(expected.Birthday, actual.Birthday);
Assert.AreEqual(expected.Age, actual.Age);
}
这似乎是一个典型的问题,所以可能是显而易见的。
来自wiki:
SHA-1产生160位(20字节)
错误:
GUID的字节数组必须恰好16字节长。
所以你不能只使用SHA1作为Guid。如果这不是与安全相关的代码,您可以尝试MD5(它是128)。
尝试以下
new Guid(hash.Take(16).ToArray())
或者你可以使用MD5散列,因为它是一个16字节的散列
var md5 = MD5.Create();
var hash = md5.ComputeHash(Encoding.Default.GetBytes(Email));
new Guid(hash);