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?
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:
UserType
s 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 UserType
s I suggest to evaluate the Jasypt Hibernate integration which provides such types.
If your database supports transparent encryption/decryption, that's probably the best thing to do.
Another option is to use you can use Jasypt, which offers a wide range of Hibernate Types to encrypt/decrypt data.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With