Transparent encryption with Hibernate

The security people at my were suggesting that we needed to create an encryption service, to securely store passwords so that even rogue DBAs could not get at them. The idea is that no matter how good your access is to the database, you shouldn’t be able to decrypt the passwords unless you have the secret key. In a solution like this, the key is generally stored offline with the application and loaded into memory sometime during startup. The encrypted data never leaves the database.

Here is what I want:

Here, EncryptedEntity is an entity that has some property encrypted. The EncryptedEntity.secretMessage property is just a String variable. All the magic happens in the Hibernate mapping file:

The interesting bits are in EncryptedStringUserType, which implements org.hibernate.usertype.UserType. Here is the code for saving the String property.

Reading and decrypting is the same, mutatis mutandis. The master key is of course set by the tests. One example may be as a global variable:

Get the full EncryptedStringUserType to see the not so gory details (notice: This is implemented with “Password Based Encryption”, but it should be simple to replace it with any Java Encryption algorithm you’d like.

About Johannes Brodwall

Johannes is Principal Software Engineer in SopraSteria. In his spare time he likes to coach teams and developers on better coding, collaboration, planning and product understanding.
This entry was posted in Java, Software Development. Bookmark the permalink.