forhas
forhas

Reputation: 11991

Securing and unsecuring data from application to DB

In my spring-maven-jpa based web app some of the data must by encrypted just before stored in the DB and then decrypted back when pooled from the DB.

So I created my encrypter service and now I wonder what should be the best implementation.

From an OO POV, I think each entity should know to secure and unsecure itself. This leads me to in inject my encrypter to an abstract base entity:

public abstract class BaseEntity {

    @Autowired(required = true)
    protected SecurityProvider securityService;

    public BaseEntity() {
    }

    /**
     * secure the entity (if required) using the securityService
     */
    @PrePersist
    @PreUpdate
    protected abstract void secure();

    /**
     * un-secure the entity (if required) using the securityService
     */
    @PostLoad
    protected abstract void unsecure();

    /*--- Getters & Setters ---*/

    public SecurityProvider getSecurityService() {
    return securityService;
    }

    public void setSecurityService(SecurityProvider securityService) {
    this.securityService = securityService;
    }
} 

As you can see, I'm trying to relay upon the @PrePersist, @PreUpdate and @PostLoad callbacks in order to do that.

At the moment I have some issue with the injection of the encrypter so I can't seen to test all the way through.

The questions is - does it look like a good practice? Can you suggest improvements or a better way?

UPDATE:

After running some tests it looks as if the @PrePersist and @PreUpdate annotations works just fine and each entity gets encrypted just before it is written to the DB. But the @PostLoad doesn't seem to work as I expected. I thought it would run each time I'm done pooling an entity from the DB but the method doesn't get invoked for some reason. Did I get the idea of @PostLoad wrong?

Upvotes: 0

Views: 97

Answers (1)

christopher
christopher

Reputation: 27346

The "Command" design pattern is a good fit for this. Basically you will have a class called "SecurityClass" with encrypt and decrypt methods.

It takes a parameter of type "entity" and performs some type of encryption on them. The advantage of using a Command design pattern is that any object of type Entity can be encrypted, and there's no need for the inheritance!

That said, using inheritance to make the methods part of the Entity class is fine, but according to the concept of "Responsibility driven design", is it the entity's job to encrypt itself, or is that more the job of some sort of outside agent?

You might not find a definitive answer for your solution, because it's essentially modelling as oppose to mathematical truth. I personally think your way is easier to understand, but implementing design patterns in your code is always a good idea.

Upvotes: 1

Related Questions