Transparently Persist and Retrieve Encrypted Data From Database
Big brother is watching… always so why not to encrypt everything. And then, auto-decrypt and encrypt our data stored in Database? Here comes Jasypt.
It’s over two months since my last post here but June and July were extremely busy and intensive months this year. First, organisation of Confitura (the biggest free conference for Java developers in Europe) was taking all of my free evenings and then, after quite nervous period in hospital, our 2nd son was born. But now, I will try to blog regularly again, so please stay tuned.
In this post I will shortly describe how we can store encrypted data in our database and retrieve it as already decrypted in a simple, transparent way using Jasypt library. Our use case will be to store Twitter Api credentials so they are safe in our database but still easy to retrieve and use to post updates in our timeline.
So what we have is a simple entity representing our settings item:
1 2 3 4 5 6 7 8 9 10
In such table we will store values for Twitter Consumer Key, Twitter Access Token and so on.
What we would like to achieve is that when we create SettingItem object with value as plain text and then we persist it, encryption is automatically performed so in the DB we have encrypted String. And of course, when we retrieve data from DB, we want to see decrypted String without additional effort, just out of the box.
Jasypt to the rescue
Jasypt is a simple encryption library written in Java. It frees developer from dealing with low level configuration details and makes whole encryption process easy and straightforward. And what is most interesting now, it also has nice integration with Hibernate allowing seamless encryption/decryption of data stored in database.
To use Jasypt and its Hibernate integration module we have to add two items to our pom:
1 2 3 4 5 6 7 8 9 10
Then we have to declare custom Hibernate type (@TypeDef) in our entity:
1 2 3 4 5 6 7 8 9 10 11 12
and after that in the same class we can mark our encryptedValue field to use this custom type:
We are almost done. Last thing we have to do is register encryptor in HibernatePBEEncryptorRegistry class. This can be done in initialization class of our application, e.g. ServletContext or simply in class with main(String args) method:
1 2 3 4 5 6 7
One important thing here is that by using System.getProperty() or System.getenv() we can safely configure our encryption mechanism, password is provided at runtime by setting proper value on server machine.
As as a summary, one short passing test showing that our solution works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30