【发布时间】:2011-07-22 18:37:59
【问题描述】:
我有这个自定义类型:
public struct PasswordString
{
private string value;
public PasswordString(string value)
{
this.value = MD5.CalculateMD5Hash(value);
}
public string Value
{
get { return this.value; }
set { this.value = MD5.CalculateMD5Hash(value); }
}
public static implicit operator PasswordString(string value)
{
return new PasswordString(value);
}
public static implicit operator string(PasswordString value)
{
return value.Value;
}
public static bool operator ==(string x, PasswordString y)
{
return x.CompareTo(y) == 0;
}
public static bool operator !=(string x, PasswordString y)
{
return x.CompareTo(y) != 0;
}
public override string ToString()
{
return Value;
}
}
public static class MD5
{
public static string CalculateMD5Hash(string input)
{
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
所以,我希望你在我的实体框架项目中使用这种类型。如何将类型映射为像字符串一样工作。
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public PasswordString Password { get; set; }
}
使用示例:
User user = new User()
{
Username = "steve",
Password = "apple"
};
System.Console.WriteLine(user.Password == "apple");
System.Console.WriteLine(user.Password);
这段代码产生:
True
1F3870BE274F6C49B3E31A0C6728957F
我的目标是查询实体框架以获得这样的结果:
var q = from u in users
where u.Username == "steve" && u.Password == "apple"
orderby u.Username
select u;
那么,我永远不需要加密密码,但它会加密存储在数据库中。
我正在尝试将此类与 EF 一起使用,但没有成功。有没有办法使用 Entity Framework 4.1 实现这一点?
【问题讨论】:
-
这是一种非常不安全的身份验证方法。不要重新发明身份验证。使用有效的现成提供程序。您可能想阅读this story of a company which made national news using a very similar scheme.
-
我无法回答这个问题,但您可能想查看Ado.Net Entity Framework Membership Provider 并节省一些时间。
标签: passwords entity-framework-4.1 code-first custom-type