Search code examples
c#encryptiongetter-setterpostsharp

Alternative to override getters and setters


I have some sensitive data which I want to keep encrypted in the db and decrypt it on the fly in the code. Since it's an existing application, I would like the encryption/decryption process to run as low as possible in the pipeline, so I don't have to amend my services level. My first solution was amending getters and setters for selected properties, to run those through my encryption helper. Then I thought it would be nice to have this wrapped in an attribute. Found Post Sharp extension that could do it, but seems to be an overkill for this scenario. Are there any other alternatives to achieve what I want to do?


Solution

  • Depending on how you use EF, you could build a wrapper on top of EF DbContext, a generic repository in which you could inject some hooks (interceptors).

    One of those interceptors would be something like ICryptographyInterceptor which would handle based on the entity type the logic for encryption (on insert) or decrypt (on retrieve) and it would not pollute your business logic or models since these interceptors would handle this task.

    An existing implementation can be found here.

    If the project is too complex for this kind of changes, maybe a ICryptographyService for transforming entities would be a better solution.