Search code examples
javasql-serverhibernatejpa

How to read encrypted database field using Hibernate


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?


Solution

  • 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 String 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.