Question

I'm using application level encryption to protect sensitive data. I need to encrypt the field before I store it in the physical database and I need to decrypt it before I show it on the user interface.

I'm applying the Repository pattern in the application.

Does the data encryption/decryption code belong inside or outside the Repository class?

My current thoughts are that when the data is at rest, encryption is an aspect of the repository and the service class using the repository should not be cluttered with this encryption code.

The service class is responsible for validation and business logic, but the encryption algorithm and how the data is stored at rest is up to the repository implementation.

Is this a reasonable practice or am I missing something?

Was it helpful?

Solution

You certainly don't want encryption in the service class.

In some sense, you actually answer your own question when you say

but the encryption algorithm and how the data is stored at rest is up to the repository implementation.

Since encryption is part of how the data is stored, it belongs inside the repository.

OTHER TIPS

I would put it in the service layer. Here's why:

Looking at it from a business rule / domain requirement perspective, is encrypting the data a requirement? Should it be validated with tests? If so, you should place it in the same place you put all of your other testable business logic. In other words, in the service.

As far as I'm concerned, business logic (what to encrypt, what not to encrypt) does not belong in the repository. The objects to be persisted should be ready for persistence (or as close as possible) when they are given to the repository. Otherwise, the repository is responsible for persistence and implementing business rules, and then you're no longer really using the repository pattern any more...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top