简体   繁体   中英

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. 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. 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.

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::

public string mob {get; set; }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM