4

I try to use database encryption for single fields with Spring and Jpa (Hibernate). Here is the part of the Entity:

@ColumnTransformer(
   read="AES_DECRYPT(UNHEX(lastname), UNHEX(SHA2('secret', 512)))",
   write="HEX(AES_ENCRYPT(?, UNHEX(SHA2('secret', 512))))"
)
private String lastname;

This uses Mysql-functions to encrypt and decrypt my field, so I do not have to care in Java.

My problem is that I cannot hardcode the passphrase in my Java-Code, but Java-Annotations only allow non-dynamic final Strings as params. How do I use a spring application property to replace the passphrase 'secret'?

I cannot use a Jpa-Converter, because I want to be able to filter and sort by lastname. I also tried to subclass MySQL5InnoDBDialect and register a StandardSQLFunction, but that does not work conceptually with @ColumnTransformer because these functions are registered in the context of JPA, not SQL. I also thought of programmatically manipulating the hibernate config before it is used to create the EntityManagerFactory, but I do not know how to do that. Any help appreciated.

Jan KB
  • 41
  • 1
  • 4
  • You entity is not a Spring managed bean so you cannot inject a Spring property. – Alan Hay Nov 10 '16 at 18:34
  • Suggestion here is to push it back to the database and have your transformer call a stored proc....http://stackoverflow.com/questions/5621422/database-encryption-in-hibernate – Alan Hay Nov 10 '16 at 18:38
  • @AlanHay I know I can create a stored procedure/db-function to hide mysql-internals. But I still need to pass the passphrase from application to the database. – Jan KB Nov 10 '16 at 19:49
  • Also I can't store the passphrase in Java-code, because my app is deployed several times for different customers, and they probably don't like the idea of a shared password across all customers. Maybe I can pass the passphrase with the connection string as a sessionVariable and use that in my db-function/stored procedure. Someone already did something like this? – Jan KB Nov 10 '16 at 20:07
  • Yes I was going to suggest that. Sounds feasible. Do you even need to pass it though? Just store it in the db. – Alan Hay Nov 10 '16 at 20:09
  • Storing the key just next to the encrypted data does not make a lot of sense from a security standpoint, I guess. – Jan KB Nov 10 '16 at 20:23
  • Five years later but if you look in the bottom of this [Github project](https://github.com/ereshzealous/spring-samples/tree/master/spring-jpa-encryption) the owner mentions two alternatives. – Avec Oct 20 '21 at 15:26

0 Answers0