5

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Admins shouldn't have access to data too (meaning can't know what exacly user storage). So my solustion is using Jasypt?
If you can bear and accept the consequences of this solution, then yes, use Jasypt (or custom UserTypes).
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.