无法在jasypt加密列上使用命名查询获取实体

时间:2013-05-13 17:21:26

标签: hibernate jasypt

我有一个使用jasypt加密ssn字段的Employee实体。以下是模拟定义:

@TypeDef(name = "encryptedString", typeClass = EncryptedStringType.class, parameters = {@Parameter(name = "encryptorRegisteredName",value = "strongHibernateStringEncryptor")})
@Entity
@Table(name="employee")
@NamedQueries(value = {
    @NamedQuery(name = "employee.getEmployeeBySSN", query = "SELECT employee from Employee employee WHERE employee.ssn=:ssn"),
    @NamedQuery(name = "employee.getEmployeeByName", query = "SELECT employee from Employee employee WHERE employee.name=:name")
    })
public class Employee {

    @Id @GeneratedValue
    private Long id;

    private String name;

    @Type(type = "encryptedString")
    private String ssn;
}

此实体包含两个用于获取员工的命名查询,一个具有名称,另一个具有ssn。 SSN字段使用jasypt加密。代码是模拟实现,因此我使用了以下基本配置:

public static void main(String[] args) throws SerialException, SQLException {

    //Configure jasypt encryptor
    PooledPBEStringEncryptor strongEncryptor = new PooledPBEStringEncryptor();
    strongEncryptor.setAlgorithm("PBEWITHMD5ANDDES");
    strongEncryptor.setPassword("jasypt");
    strongEncryptor.setPoolSize(2);

    //Register it with hibernate
    HibernatePBEEncryptorRegistry registry = HibernatePBEEncryptorRegistry.getInstance();
    registry.registerPBEStringEncryptor("strongHibernateStringEncryptor", strongEncryptor);

    //Get an entity manager factory
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("helloworld");

    //Get an entity manager
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    //Create an employee
    Employee employee = new Employee();
    employee.setName("Vaibhav");
    employee.setSsn("1234567");
    em.persist(employee);

    tx.commit();

    EntityTransaction newtx = em.getTransaction();
    newtx.begin();

    //Search an employee with ssn
    Query queryObject1 = em.createNamedQuery("employee.getEmployeeBySSN");
    queryObject1.setParameter("ssn", "1234567");

    //No results here
    List employees1 = queryObject1.getResultList();

    newtx.commit();
    em.close();

}

employees1列表中没有结果。但是,当我运行以下命名查询时,我能够在employee对象中看到解密的ssn。

Query queryObject = em.createNamedQuery("employee.getEmployeeByName");
queryObject.setParameter("name", "Vaibhav");
List employees = queryObject.getResultList();
Employee employee1 = (Employee)employees.get(0);

我无法理解我的代码中是否存在错误,或者hibernate应该如何工作。 在文档Integrating Jasypt with Hibernate 3.x or 4.x中,写有:

  

但加密设置了对Hibernate使用的限制:安全性   标准确定了两种不同的加密操作   相同的数据不应返回相同的值(由于使用随机数   盐)。因此,没有设置的字段   持久化时加密可以是你的WHERE子句的一部分   搜索他们所属实体的查询。

因此,这意味着无法对加密字段执行搜索操作。

1 个答案:

答案 0 :(得分:1)

我使用的是随机盐生成器。添加零盐生成器后,我能够解决问题:

strongEncryptor.setSaltGenerator(new ZeroSaltGenerator());