Linq-to-Sql实体中字段值的加密 [英] Encryption of a field's value in a Linq-to-Sql Entity

查看:66
本文介绍了Linq-to-Sql实体中字段值的加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对Linq2Sql实体上的某些字段进行加密.我还希望加密和解密的过程对实体的使用者是透明的,这意味着一旦将实体加载到内存中,该字段将显示为常规值字符串(已解密),但是当持久化到相同字段时,这些字段将被加密数据库.

I need to encrypt some fields on my Linq2Sql Entity. I would also like the process of encryption and decryption be transparent to the consumer of the entity, meaning that once the entity is loaded into memory the field is presented as regular value string (decrypted), but the same fields gets encrypted when being persisted to the database.

推荐答案

还有另一种选择:您可以使用例如隐藏"实际属性. protected 访问修饰符,并在实体部分类中添加一个假" public 属性,该属性将在getter/setter中对此 internal 进行加密/解密,因此对消费者而言将是透明的:

There is another option: you could "hide" the actual property with e.g. protected access modifier and the add a "fake" public property to the entity partial class which will encrypt/decript this internal in getter/setter, so it will be transparent to the consumer:

.dbml文件:

<Column Name="Password" 
    Member="PasswordInternal" 
    AccessModifier="Protected" 
    Type="System.String" 
    DbType="Varchar(64) NOT NULL" 
    CanBeNull="false" />

,然后在部分类中:

public partial class YourEntity
{
   public string Password
   {
        get
        {
            return Crypter.Decrypt(this.PasswordInternal)
        }
        set
        {
            this.PasswordInternal = Crypter.Encrypt(value)
        }
   }
}

这篇关于Linq-to-Sql实体中字段值的加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆