How to properly encrypt data using JPA converters and Spring Data JPA

July 21, 2017

TL;DR: all code is directly available on GitHub: https://github.com/damienbeaufils/spring-data-jpa-encryption-example

Each time I want to encrypt entity fields values with JPA converters, I end up reading this blog post. This example is clear and functional, but has no unit or integration tests, and I thought the code could be more decoupled to avoid duplication when having multiple converters.

So I wrote an example using Spring Boot and Spring Data JPA, with a User entity which have different fields: id (a Long), firstName (a String), lastName (a String), email (a String), birthDate (a LocalDate) and creationDate (a LocalDateTime). All fields except id are encrypted in database using AES algorithm.

Encryption is enabled on fields using different JPA converters: StringCryptoConverter, LocalDateCryptoConverter and LocalDateTimeCryptoConverter. This is verified with UserRepositoryTest integration test, and all converters are unit tested.

Encryption key is empty by default (see example.database.encryption.key configuration key in application.yml). You have to provide an encryption key in configuration or specify it in options when running application.

Feel free to fork & enjoy!

Nifty tech tag lists from Wouter Beeftink | Page content generated from commit: fd23f50