DataBase encryption in Hibernate

17,565

Solution 1

Try this:

Put an attribute in your entity:

private byte[]  encryptedBody;

Use this getter and setters:

@Column(columnDefinition= "LONGBLOB", name="encryptedBody") 
@ColumnTransformer(
  read="AES_DECRYPT(encryptedBody, 'yourkey')", 
  write="AES_ENCRYPT(?, 'yourkey')")
public byte[]  getEncryptedBody() {
    return encryptedBody;
}

public void setEncryptedBody(byte[]  encryptedBody) {
    this.encryptedBody = encryptedBody;
}

And then when you retrive the column use:

private final Charset UTF8_CHARSET = Charset.forName("UTF-8");

String decodeUTF8(byte[] bytes) {
    return new String(bytes, UTF8_CHARSET);
}

String s = decodeUTF8(entity.getEncryptedBody());

BEWARE: AES_DECRYPT and AES_ENCRYPT belong to MySQL. If you have a different data base engine find similar functions.

Hope this helps.

Solution 2

You can use the @ColumnTransformer annotation like this:

@ColumnTransformer(
    read =  "pgp_sym_decrypt(" +
            "    storage, " +
            "    current_setting('encrypt.key')" +
            ")",
    write = "pgp_sym_encrypt( " +
            "    ?, " +
            "    current_setting('encrypt.key')" +
            ") "
)
@Column(columnDefinition = "bytea")
private String storage;

This way, Hibernate will be able to encrypt the entity attribute when you persist or merge it and decrypt it when you read the entity.

Solution 3

I think that you are looking for column transformers. You can find how to do it in the Hibernate reference:

http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-column-read-and-write

I hope that helps!

Solution 4

You could use jasypt. It has an Hibernate integration that allows you to encrypt properties while saving (and decrypt while loading).

http://www.jasypt.org/hibernate.html

Share:
17,565
Chandrasekhar
Author by

Chandrasekhar

Updated on June 17, 2022

Comments

  • Chandrasekhar
    Chandrasekhar almost 2 years

    How can encrypt the data base fields when using the hibernate?

    We have developed the product some of the clients are using that application Some clients is asking about the data base encryption Is there any possible to encrypt the data in application level with out more changes in the code.

    Please give me the suggestion as soon as possible.