How to read encrypted database field using Hibernate

11,336

Solution 1

I don't see how you might do that. But from what I've read, ENCRYPTBYPASSPHRASE uses triple-DES. So you might encrypt the data yourself and persist it as is with Hibernate. Here's how it would look like to make it transparent (except for queries, obviously)

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

where CryptoUtils would be responsible for storing the secret key and encrypting/decrypting using triple-DES (which is natively supported in the JDK : see http://download.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html#Cipher)

Just make sure to test it and make sure that your decryption is able to decrypt what SQL-Server has encrypted, and vice-versa.

Solution 2

Sounds like you are looking for org.hibernate.annotations.ColumnTransformer

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

Solution 3

Reviving an old thread, but I was having a similar requirement and found that Jasypt has some very nice support for this.

Once Jasypt configured, it's as easy as adding a "@Type(type="encryptedString")" annotation:

@Column(name = "password")
@Type(type="encryptedString")
public String getPassword() {
    return password;
}
Share:
11,336
Marquinio
Author by

Marquinio

Updated on June 30, 2022

Comments

  • Marquinio
    Marquinio almost 2 years

    I'm working on a project where some database table fields need to be encrypted. The way this will be done is using Microsoft SQL Server built-in encryption/decryption function:

    ENCRYPTBYPASSPHRASE('PASSPHRASE',‘text’)
    
    DECRYPTBYPASSPHRASE ('12',password)
    

    So to insert data the SQL will be like this:

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

    And to read data the SQL will be this way:

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

    So my question is how I can I make use of this in Hibernate using my existing OR mappings? I'm using JPA Annotations. Is there an easy way to do this with JPA annotations?