简体   繁体   中英

C#, Dapper, POCO and Encrypt/Decrypt

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

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;
    }
}

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