0

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.

Abhishek Singh
  • 369
  • 2
  • 17

1 Answers1

3

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();
    }
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240