0

I have this POCO class:

class Users
{
    public string User { get; set; }
    public string Password { get; set; }

    private string Encrypt(string plainText)
    {
        ...
        return encryptedText;
    }
    private string Decrypt(string cipherText)
    {
        ...
        return decryptedText;
    }

How can I do to Encrypt/Decrypt Password field when I read data from my database and when I access my POCO object from C#?

I'm tried to use sometingh like this:

class Users
{
    private string _password;

    public string User { get; set; }
    public string Password
    {
        get
        {
            return Encriptar(_password);
        }
        set
        {
            _password = Desencriptar(value);
        }
    }

    private string Encrypt(string plainText)
    {
        ...
        return encryptedText;
    }
    private string Decrypt(string cipherText)
    {
        ...
        return decryptedText;
    }

But when the objects are filled with data from my database, all is ok, the Password field decrypts correctly, but when I access an object from C# to show in text field, the get property enrypts again my data :/

Daniel Q.
  • 39
  • 6
  • 3
    If you have a function that decrypts a password, you are doing it wrong. [Required reading](http://stackoverflow.com/q/1054022/335858). – Sergey Kalinichenko Jan 20 '17 at 01:20
  • 3
    **Do not encrypt passwords**, when the attacker gets the DB he will also get the encryption key. Iterate over an HMAC with a random salt for about a 100ms duration and save the salt with the hash. Use functions such as `password_hash`/`password_verify`, `PBKDF2` (aka `Rfc2898DeriveBytes`), `Bcrypt` and similar functions. The point is to make the attacker spend a lot of time finding passwords by brute force. – zaph Jan 20 '17 at 01:47

1 Answers1

0

This has nothing to do with Dapper. Also consider the comments posted by others to your question.

Following just suggests how to avoid decryption twice in get block.

private string _password;
private bool _isDecrypted = false;
public string Password
{
    get
    {
        if(_isDecrypted == false)
        {
            _password = Decrypt(_password);
            _isDecrypted = true;
        }
        return (_password);
    }
    set
    {
        _password = Encrypt(value);
        _isDecrypted = false;
    }
}
Amit Joshi
  • 15,448
  • 21
  • 77
  • 141