【问题标题】:How to read encrypted database field using Hibernate如何使用 Hibernate 读取加密的数据库字段
【发布时间】:2011-08-17 19:10:57
【问题描述】:

我正在做一个需要加密一些数据库表字段的项目。这样做的方式是使用 Microsoft SQL Server 内置的加密/解密功能:

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

所以我的问题是如何使用现有的 OR 映射在 Hibernate 中使用它?我正在使用 JPA 注释。 有没有使用 JPA 注释的简单方法?

【问题讨论】:

    标签: java sql-server hibernate jpa


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      恢复一个旧线程,但我有类似的要求,发现Jasypt 对此有一些非常好的支持。

      配置 Jasypt 后,就像添加“@Type(type="encryptedString")”注解一样简单:

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

      【讨论】:

        【解决方案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 已加密的内容,反之亦然。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-19
          • 1970-01-01
          相关资源
          最近更新 更多