Get/Set 中加密/解密对象属性的设计模式

web*_*orm 1 c# encryption cryptography getter-setter

我正在尝试找到一种好的设计模式,该模式允许我将用户的私人信息存储为加密的密文,同时使加密/解密对对象的用户来说是无缝的。

例如......假设我有一个 Patient 对象,该对象的属性是一些私人信息,例如社会安全号 (SSN)。我想将其作为加密值存储在数据库中,但允许应用程序代码使用以下语法获取/设置 SSN:

// Getting the unencrypted SSN
var currentSSN = selectedPatient.SSN;

// Setting the unencrypted SSN, but will be encrypted in Setter
selectedPatient.SSN = "555-55-5555";
Run Code Online (Sandbox Code Playgroud)

我尝试将加密/解密放在 getter 和 setter 中......

public string SSN
{
  get 
  {
    return MyEncryptionClass.Decrypt(this.SSN);
  }
  set
  {
    value =  MyEncryptionClass.Encrypt(value);
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:假设密钥和初始化向量均由加密/解密方法处理。我想重点关注获取/设置部分。

问题是我发现 SSN 以纯文本形式存储在数据库记录中,即使我在 Setter 中有 Encrypt 方法。我可以通过调试确认加密例程实际上返回了正确的密文,但它似乎没有存储在数据库记录中。我的想法是 Get/Set 有点循环。通过设置值,我调用解密方法,因此存储在记录中的内容实际上已被解密。

人们是否发现了一种有效的模式,可以让对象的使用者无缝地进行加密/解密。我想避免他们必须手动调用加密/解密方法。

编辑-我正在使用实体框架 v6

Ken*_*eth 5

一个简单的模式可能如下:

// this property will be persisted in the database, but can't be modified from outside
public string SSN { get; private set; }

// the attribute will make sure this doesn't get mapped to the db
// this property uses the other property as a backing field with proper conversions
[NotMapped]
public string SSNDecrypted
{
  get 
  {
    return MyEncryptionClass.Decrypt(this.SSN);
  }
  set
  {
    this.SSN =  MyEncryptionClass.Encrypt(value);
  }
}
Run Code Online (Sandbox Code Playgroud)