2011-05-03 79 views
2

我工作的一个项目中,一些数据库表字段需要加密读取加密数据库字段。这将实现的方法是使用Microsoft SQL Server内置的加密/解密功能:如何使用Hibernate

ENCRYPTBYPASSPHRASE('PASSPHRASE',‘text’) 

DECRYPTBYPASSPHRASE ('12',password) 

所以要插入数据的SQL将是这样的:

insert into login_details(uid,username,password) values(1,'smith',EncryptByPassPhrase('12',’XXX’)) 

并读取数据的SQL会是这个样子:

select uid,username, DECRYPTBYPASSPHRASE ('12',password) as Password from login_details 

所以我的问题是如何,我可以用我的现有或映射我使用这个在Hibernate中?我正在使用JPA注释。 有没有简单的方法来做到这一点与JPA批注?

回答

3

我不知道你会如何做。但从我读到的,ENCRYPTBYPASSPHRASE使用三重DES。所以你可以自己加密数据并像Hibernate那样保存它。下面是它看起来像使它透明(除查询,很明显)

@Entity 
public class LoginDetails { 
    @Column(name = "password") 
    private byte[] encryptedPassword; 

    @Transient 
    private String password; 

    public void getPassword() { 
     if (password == null) { 
      password = CryptoUtils.decrypt(encryptedPassword); 
     } 
     return password; 
    } 

    public void setPassword(String password) { 
     this.encryptedPassword = CryptoUtils.encrypt(password); 
     this.password = password; 
    } 
} 

其中CryptoUtils将负责存储密钥和加密/使用三重DES(这是在JDK原生支持解密:请参阅http://download.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#Cipher

只要确保测试它并确保您的解密能够解密SQL-Server已加密的内容,反之亦然。

+0

感谢我给它一个尝试。 – Marquinio 2011-05-04 02:47:53

8

听起来像是你正在寻找org.hibernate.annotations.ColumnTransformer

@Column(name = "pswd") 
@ColumnTransformer(write="EncryptByPassPhrase('12',?)", read="DECRYPTBYPASSPHRASE ('12',pswd)") 
public String getPassword() { 
    return password; 
} 
6

回想起一个古老的线程,但我有一个类似的要求,发现Jasypt有这一些非常好的支持。

一旦配置Jasypt,这是因为加入了“@Type(type="encryptedString")”注释为简单:

@Column(name = "password") 
@Type(type="encryptedString") 
public String getPassword() { 
    return password; 
}