简体   繁体   English

我如何在ASP.NET MVC 5中的模型中加密和解密

[英]How do i encrypt and decrypt in model in asp.net mvc 5

I have Model named Users in ASP.NET MVC 5. I have Encrypt() and Decrypt() Extension Methods to Encrypt and Decrypt string respectively. 我在ASP.NET MVC 5中具有名为Users的模型。我具有Encrypt()和Decrypt()扩展方法,分别用于加密和解密字符串。 I want to encrypt and decrypt data while sving and fetching from database. 我想在从数据库中获取数据时进行加密和解密。 So, I used: 因此,我使用了:

private string _mob;
public string mob
    {
        get
        {
            return _mob.Decrypt();
        }
        set
        {
            _mob = value.Encrypt();
        }
    }

But I am unable to achieve my goal. 但是我无法实现我的目标。 When I use 当我使用

public string mob
    {
        get
        {
            return _mob;
        }
        set
        {
            _mob = value.Encrypt();
        }
    }

I get encryption done but as soon as I add Decrypt() in get{} there is no encryption/decryption done. 我完成了加密,但是一旦在get {}中添加Decrypt(),就不会完成加密/解密。 I see plain text data in database. 我在数据库中看到纯文本数据。

EF will use the property accessors when storing the data in the database, not the backing field, so if you want the encrypted value stored you need to return the encrypted value from the getter. EF在将数据存储在数据库中而不是在后备字段时将使用属性访问器,因此,如果要存储加密的值,则需要从getter返回加密的值。

Since you probably want a property that returns the decrypted value as well you probably want a separate unmapped property for the decrypted text. 由于您可能需要一个返回解密值的属性,因此您可能需要一个单独的未映射属性来处理解密的文本。 You can use the [NotMapped] attribute so EF doesn't try to save it to the database as well:: 您可以使用[NotMapped]属性,因此EF也不会尝试将其保存到数据库中:

public string mob {get; set; }

[NotMapped]
public string mobDecrypted
{
    get
    {
        return mob.Decrypt();
    }
    set
    {
        mob = value.Encrypt();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.Net中加密文件并在Silverlight中解密? - How can I encrypt a file in ASP.Net and decrypt it in Silverlight? 如何在ASP.NET中加密和解密我的Cookie - How can i encrypt and decrypt my Cookies in ASP.NET 我如何? 服务器(ASP.NET)中的简单加扰/加密字符串,而JavaScript中的加扰/解密字符串 - how do I? simple scramble/encrypt string in server (ASP.NET) and unscramble/decrypt in javascript 尝试在asp.net mvc中加密和解密密码 - trying to encrypt & decrypt password in asp.net mvc ASP.NET Core MVC加密/解密QueryString值 - ASP.NET Core MVC Encrypt/Decrypt QueryString Values 如何使在asp.net MVC加密? - how to make encrypt in asp.net mvc? 如何在ASP.NET MVC的父域模型中将此子模型引用传递给虚拟ICollection? - How do I pass this child model reference to a virtual ICollection in parent domain model in ASP.NET MVC? 如何在ASP.NET MVC 2应用程序中进行复杂的模型验证? - How do I do complex model validations in an ASP.NET MVC 2 application? 如何在asp.net mvc 2中进行整数模型验证 - How to do Integer model validation in asp.net mvc 2 如何在 Asp.Net Core MVC 中进行自定义 model 绑定 - How to do custom model binding in Asp.Net Core MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM