This is an example of spring data jpa with encryption, by means of mapping to an AttributeConverter
This example does the following:
- the instance of class UserDetails is encrypted and put into the field encrypted_data of the sql table users
- the instance of class UserDetails is accessible via the JPA entity class User
- Note that there is a dummy sql table definition here that contains no data, it exists for the purpose of mapping its fields to class UserDetails by means of JPA
- The encryption/decryption is done transparently by converter class UserDetailsEncConverter.java class, which is a spring component that also implements the AttributeConverter interface. The converter is called transparently by JPA when the encrypted UserDetails object is accessed.
- the UserData instance is serialized into json by means of jackson, the serialized data is then encrypted/decrypted by using the data key, the data key is generated to encrypt a subset of the record instances.
- The encrypted data key is stored together with the encrypted record data.
- The UserDetailsEncConverter.java bean uses the injected CryptoBeanInterface component, this component handles the creation of the per record data key, as well as the access to the encrypted data key.
- The UserDetailsEncConverter.java bean uses template class EncryptedFieldsJPAConverterImpl, this template implementation class serializes the object instance into json (by means of jackson), accesses the record key, and then encrypts/decrypts record data with the record key.
- There is data key, each data key is used for the encryption of one or more records. This data key is encrypted by a master key and stored in encrypted form together with the encrypted data.
- There are two modes of work. Each of the modes is implementing a spring component, that implements interface CryptoBeanInterface
- A test mode, when both the master and per record data key is generated randomly. This is implemented by the TestCryptoBean this bean is enabled when spring parameter
encryption.mode
is set totest
- A run mode, when the data key is generated by the KMS service of AWS, and the master key is implicitly handled by AWS. This is implemented by the KmsCryptoBean this bean is enabled when spring parameter
encryption.mode
is set tokms
; Note that here there are additional spring parameters that need to be set, namelyaws.datakey.masterkeyId
and optionallyaws.datakey.keyCacheSize
- A test mode, when both the master and per record data key is generated randomly. This is implemented by the TestCryptoBean this bean is enabled when spring parameter
A unit test puts the test checks the test mode. Here you need to start the postgress docker instance by means of docker-compose up -d
, then run the tests as part of gradle build
Note that you also have a psql.sh script, this runs pql
and connects it to the test db hosted by the docker instance.