Get/Set 中 encrypting/decrypting 对象属性的设计模式
Design pattern for encrypting/decrypting object properties in Get/Set
我正在尝试找到一个好的设计模式,它允许我将用户的私人信息存储为加密的密文,同时使 encryption/decryption 与对象的用户无缝连接。
例如...假设我有一个 Patient 对象,对象上的 属性 是一些私人信息,例如社会安全号码 (SSN)。我想将其作为加密值存储在数据库中,但允许应用程序代码使用诸如 ...
之类的语法 get/set SSN
// Getting the unencrypted SSN
var currentSSN = selectedPatient.SSN;
// Setting the unencrypted SSN, but will be encrypted in Setter
selectedPatient.SSN = "555-55-5555";
我尝试将 encryption/decryption 放在 getter 和 setter 中 ...
public string SSN
{
get
{
return MyEncryptionClass.Decrypt(this.SSN);
}
set
{
value = MyEncryptionClass.Encrypt(value);
}
}
注意:假设密钥和初始化向量都由 Encrypt/Decrypt 方法处理。我想专注于 Get/Set 部分。
问题是我发现 SSN 以纯文本形式存储在数据库记录中,即使我在 Setter 中使用了 Encrypt 方法。我可以通过调试确认 Encrypt 例程实际上返回了正确的密文,但它似乎并没有像这样存储在数据库记录中。我的想法是 Get/Set 有点循环。通过设置我调用解密方法的值,存储在记录中的内容实际上被解密了。
人们是否发现了一种模式可以让 encryption/decryption 无缝连接到对象的使用者。我想避免他们必须手动调用 encrypt/decrypt 方法。
编辑 - 我正在使用 Entity Framework v6
一个简单的模式如下:
// 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);
}
}
我正在尝试找到一个好的设计模式,它允许我将用户的私人信息存储为加密的密文,同时使 encryption/decryption 与对象的用户无缝连接。
例如...假设我有一个 Patient 对象,对象上的 属性 是一些私人信息,例如社会安全号码 (SSN)。我想将其作为加密值存储在数据库中,但允许应用程序代码使用诸如 ...
之类的语法 get/set SSN// Getting the unencrypted SSN
var currentSSN = selectedPatient.SSN;
// Setting the unencrypted SSN, but will be encrypted in Setter
selectedPatient.SSN = "555-55-5555";
我尝试将 encryption/decryption 放在 getter 和 setter 中 ...
public string SSN
{
get
{
return MyEncryptionClass.Decrypt(this.SSN);
}
set
{
value = MyEncryptionClass.Encrypt(value);
}
}
注意:假设密钥和初始化向量都由 Encrypt/Decrypt 方法处理。我想专注于 Get/Set 部分。
问题是我发现 SSN 以纯文本形式存储在数据库记录中,即使我在 Setter 中使用了 Encrypt 方法。我可以通过调试确认 Encrypt 例程实际上返回了正确的密文,但它似乎并没有像这样存储在数据库记录中。我的想法是 Get/Set 有点循环。通过设置我调用解密方法的值,存储在记录中的内容实际上被解密了。
人们是否发现了一种模式可以让 encryption/decryption 无缝连接到对象的使用者。我想避免他们必须手动调用 encrypt/decrypt 方法。
编辑 - 我正在使用 Entity Framework v6
一个简单的模式如下:
// 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);
}
}