对你的一个实体说你有一个属性,当你需要保存到数据库时,它需要加密,但是当你在代码中处理它时,你只需要简单地对待它文本。存储敏感数据的EntityFramework
现在,我有这样的设置:
public class MyEntity
{
[SecureStringAttribute]
public string SecureString {get;set;}
}
我的DbContext,这就是 “神奇” 发生。
public MyDbContext()
: base("conn")
{
((IObjectContextAdapter)this).ObjectContext.SavingChanges += ObjectContextOnSavingChanges;
((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += ObjectContextOnObjectMaterialized;
}
private void ObjectContextOnObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
{
DecryptSecureString(e.Entity);
}
private void ObjectContextOnSavingChanges(object sender, EventArgs e)
{
EncryptSecureStrings(sender as ObjectContext);
}
private void DecryptSecureString(object entity)
{
if (entity != null)
{
foreach (
PropertyInfo propertyInfo in
EntityFrameworkSecureStringAttribute.GetSecureStringProperties(entity.GetType()))
{
string encryptedValue = propertyInfo.GetValue(entity) as string;
if (!string.IsNullOrEmpty(encryptedValue))
{
string decryptedValue = EncDec.Decrypt(encryptedValue);
propertyInfo.SetValue(entity, decryptedValue);
}
}
}
}
private void EncryptSecureStrings(ObjectContext context)
{
if (context != null)
{
foreach (ObjectStateEntry objectStateEntry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified).Where(x => x.Entity != null))
{
object[] data = new object[objectStateEntry.CurrentValues.FieldCount];
objectStateEntry.CurrentValues.GetValues(data);
PropertyInfo[] properties =
EntityFrameworkSecureStringAttribute.GetSecureStringProperties(objectStateEntry.Entity.GetType());
foreach (PropertyInfo propertyInfo in properties)
{
string currentValue = objectStateEntry.CurrentValues[propertyInfo.Name] as string;
if (!string.IsNullOrEmpty(currentValue))
{
int index = objectStateEntry.CurrentValues.GetOrdinal(propertyInfo.Name);
string newVal = EncDec.Encrypt(currentValue);
objectStateEntry.CurrentValues.SetValue(index, newVal);
}
}
}
}
}
它直截了当我只是在保存和加载时加密/解密字符串。但是,如果我做到以下几点:
MyEntity entity = new MyEntity(){SecureString= "This is secret!!"};
dbContext.SaveChanges();
此时entity.SecureString
已经加密,并且与此对象的任何进一步的使用将是不正确的。
你有没有考虑过离开'单独SecureString'并将其标记为'protected'再曝使用'SecureString'作为其后备存储集中化加密了'DecryptedString'财产的get /解密逻辑/该属性的集合?属性/反射解决方案似乎有点过分。 – 2014-09-04 13:16:02