Home > Back-end >  How to automatically convert encrypted string column to decimal in C#?
How to automatically convert encrypted string column to decimal in C#?

Time:03-11

I'm working on an application in .Net Core 3.1 where we need to encrypt some database columns. Initially we tried to use SQL Server's own column-level encryption. But during the tests we came across some problems and conflicts with the certificate, because every time we changed the columns, the certificate stopped working.

Therefore, we decided to try another approach, applying encryption in the application itself. After some research, I found two packages:

  • EntityFrameworkCore.DataEncryption
  • EntityFrameworkCore.EncryptColumn

I followed some examples I found on the internet, and implemented an example using the EntityFrameworkCore.DataEncryption package. The problem is that encryption can only be applied to string-type fields and the data I need to encrypt is decimal, such as salary. As the application performs several operations involving these decimal fields, I would like to somehow perform the automatic conversion of the fields during reading and writing.

Example:

public class Produto
{
    [Key]
    public int IdProduto { get; set; }

    public string NomeProduto { get; set; }

    [Encrypted]
    public string Valor { get; set; }

    [Encrypted]
    public string Desconto { get; set; }

    [Encrypted]
    public string ValorVenda { get; set; }
}

In my Product class, I need to encrypt some fields, they need to be string to work. I would like to somehow check if the field has the annotation [Encrypted] and when performing the get, it would be automatically converted to decimal and before persisting in the database, convert it again to string.

I've tried examples I've found, but so far without success. Could someone please tell me if this is possible and if so how could it be done?

Thank you

CodePudding user response:

You can use reflection and check that the type/object has the [Encryption] attribute. I would adapt the code from this page:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/accessing-attributes-by-using-reflection

The key is to use reflection. You can read a class properties, methods etc to check for attributes.

CodePudding user response:

Can you try something like adding an additional property for each of the fields you want encrypted, but don't map it to the database table. For example for ValorVenda:

// omit the [Encrypted] attribute
public string ValorVenda {get; set;}

[NotMapped]
public string ValorVendaLocal 
{ 
    get 
    { 
        // return decrypted ValorVenda 
    } 
    set
    {
        // ValorVenda = ... encrypt ValorVendaLocal
    }
} 
  • Related