對你的一個實體說你有一個屬性,當你需要保存到數據庫時,它需要加密,但是當你在代碼中處理它時,你只需要簡單地對待它文本。存儲敏感數據的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