保护和取消保护从应用程序到数据库的数据

时间:2012-12-02 12:02:20

标签: database security jpa encryption jpa-2.0

在我的基于spring-maven-jpa的网络应用程序中,一些数据必须在存储到数据库之前加密,然后在从数据库汇集时解密回来。

所以我创建了我的加密服务,现在我想知道什么应该是最好的实现。

从OO POV,我认为每个实体都应该知道自己的安全和不安全。这导致我将加密器注入抽象基础实体:

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

正如你所看到的,我试图转发@PrePersist,@ PreUpdate和@PostLoad回调以便做到这一点。

目前我在注入加密器时遇到了一些问题,所以我无法一直测试。

问题是 - 它看起来像是一种好习惯吗?你能提出改进或更好的方法吗?

更新:

运行一些测试之后,看起来好像@PrePersist和@PreUpdate注释工作得很好,每个实体在写入数据库之前就被加密了。但@PostLoad似乎并没有像我预期的那样发挥作用。我认为每次我从数据库中汇集实体时它都会运行,但该方法由于某种原因没有被调用。我是否认为@PostLoad错了?

1 个答案:

答案 0 :(得分:1)

“命令”设计模式非常适合这种情况。基本上,您将拥有一个名为“SecurityClass”的类,其中包含加密和解密方法。

它采用“entity”类型的参数,并对它们执行某种类型的加密。使用Command设计模式的优点是可以加密任何Entity类型的对象,并且不需要继承!

也就是说,使用继承来使方法成为Entity类的一部分很好,但是根据“责任驱动设计”的概念,实体的工作是加密自身,还是更多的某种工作呢?外部代理人?

您可能找不到适合您解决方案的明确答案,因为它基本上是建模而不是数学真理。我个人认为您的方式更容易理解,但在代码中实现设计模式总是一个好主意。