簡體   English   中英

如何在Entity Framework Code First中加密數據?

[英]How do I encrypt data in Entity Framework Code First?

我一直在嘗試並且未能找到使用Entity Framework Code First加密SQL數據的好方法。 我必須在前面加上我在Azure中托管並且無法訪問本機SQL加密。

SecurEntity獲取一個頁面,我已經完全實現了一種利用SaveChanges和ObjectMaterialized來處理實體加密/解密的方法,但在測試中我發現這一點太不可靠了。

以下是一些實現的示例:

public override int SaveChanges()
{
    var pendingEntities = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager
        .GetObjectStateEntries(EntityState.Added | EntityState.Modified)
        .Where(en => !en.IsRelationship).ToList();

    foreach (var entry in pendingEntities) //Encrypt all pending changes
        EncryptEntity(entry.Entity);

    int result = base.SaveChanges();

    foreach (var entry in pendingEntities) //Decrypt updated entities for continued use
        DecryptEntity(entry.Entity);

    return result;
}

void ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
{
    DecryptEntity(e.Entity);
}

我已經看到其他帖子通過輔助屬性手動加密/解密,如下所示:

public Value { get; set; }

[NotMapped]
public DecryptedValue
{
    get { return Decrypt(this.Value); }
    set { this.Value = Encrypt(value); }
}

這肯定會奏效,但我發現這種方法不太理想。 使用這種方法時,所有開發人員都必須瀏覽所有加密屬性,以找出他們可以使用的屬性。

最理想的解決方案是讓我能夠在數據訪問級別覆蓋每個值的獲取/設置。 有沒有辦法做到這一點? 如果沒有,我如何使用Entity Framework - Code First實現數據加密,以便易於維護和使用?

我有好消息。 我使用SaveChanges / ObjectMaterialized方法遇到的不穩定性是由於在DbContext實際執行保存之前不會調用DetectChanges()

在從ObjectStateManager提取Added / Modified記錄之前,我可以通過調用DetectChanges()來解決這個問題。 這清除了導致不一致加密行為的任何對象狀態怪異。

結果代碼是:

public override int SaveChanges()
{
    var contextAdapter = ((IObjectContextAdapter)this);

    contextAdapter.ObjectContext.DetectChanges();

    var pendingEntities = contextAdapter.ObjectContext.ObjectStateManager
        .GetObjectStateEntries(EntityState.Added | EntityState.Modified)
        .Where(en => !en.IsRelationship).ToList();

    foreach (var entry in pendingEntities) //Encrypt all pending changes
        EncryptEntity(entry.Entity);

    int result = base.SaveChanges();

    foreach (var entry in pendingEntities) //Decrypt updated entities for continued use
        DecryptEntity(entry.Entity);

    return result;
}

編輯 - 添加了一個示例DataContext,以查看我的加密所有實體的端到端解決方案。 注意:您不必使用自定義屬性來加密屬性。 資源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM