Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt data with Hibernate to prevent accessing column values

I develop a Java web service using Hibernate to connect with the DB. Users will store data that no one should access directly, even from the DB.

Is there a possibility to generate for every user a key that encrypts/decrypts data in the DB. How to share access between a group of users?

How to do it using Hibernate?

like image 845
Mr Jedi Avatar asked Mar 23 '14 14:03

Mr Jedi


2 Answers

As for storing encrypted content in the database through Hibernate I suggest you invest some time to study Hibernate Encryption of Database Completely Transparent to Application. It suggests a number of options:

  • instead of a plain JDBC connection use JDBC-over-SSL (no traffic sniffing between application and database)
  • rather than encrypting specific content in the database use something like TrueCrypt to encrypt the hard drive on which the data is stored
  • use custom Hibernate UserTypes which encrypt/decrypt data on-the-fly (i.e. instead of String you'd use EncryptedString)

The reason why the first two are often superior to what you seem to attempt is this quote from the other question

bear in mind that any solution with client-side encryption will render all your db data unusable outside of the client, ie, you will not be able to use nice tools like a jdbc client or MySQL query browser, etc.

However, if still want to encrypt/decrypt data on-the-fly using custom Hibernate UserTypes I suggest to evaluate the Jasypt Hibernate integration which provides such types.

like image 124
Marcel Stör Avatar answered Oct 16 '22 03:10

Marcel Stör


Transparent encryption/decryption

If your database supports transparent encryption/decryption, that's probably the best thing to do.

Jasypt

Another option is to use you can use Jasypt, which offers a wide range of Hibernate Types to encrypt/decrypt data.

Using a @ColumnTransformer

A very easy way to encrypt/decrypt an entity attribute is to use a @ColumnTransformer 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 upon fetching the entity.

like image 2
Vlad Mihalcea Avatar answered Oct 16 '22 03:10

Vlad Mihalcea