Enterprise Java

How to use a JPA Type Converter to encrypt your data

A few days ago, I read an interesting article by Bear Giles about Database encryption using JPA listeners from 2012. He discusses his requirement for an encryption solution and provides a code example with JPA listeners. His main requirements are:

  • provide a transparent encryption that does not affect the application,
  • be able to add the encryption at deployment time,
  • develop application and security/encryption by two different teams/persons.

And I completely agree with him. But after 1.5 years and a spec update to JPA 2.1, JPA listeners are not the only solution anymore. JPA 2.1 introduced type converter, which can be used to create a maybe better solution.

General information and setup

This example expects, that you have some basic knowledge about JPA type converter. If you want to read in more detail about type converters, check my previous article on JPA 2.1 – How to implement a Type Converter.

The setup for the following example is quiet small. You just need a Java EE 7 compatible application server. I used Wildfly 8.0.0.Final which contains Hibernate 4.3.2.Final as JPA implementation.

Creating the CryptoConverter

Payment information like a credit card number are confidential information that should be encrypted. The following code snippet shows the CreditCard entity which we will use for this example.

@Entity
public class CreditCard {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String ccNumber;

    private String name;

    ...
}

As we pointed out in the beginning, the encryption should work in a transparent way. That means, that the application is not affected by the encryption and that it can be added without any changes to the existing code base. For me, this also includes the data model in the database because it is often created by some application specific scripts which shall not be changed. So we need a type converter that does not change the data type while encrypting and decrypting the information.

The following code snippet shows an example of such a converter. As you can see, the converter is quite simple. The convertToDatabaseColumn method is called by hibernate before the entity is persisted to the database. It gets the unencrypted String from the entity and uses the AES algorithm with a PKCS5Padding for encryption. Then a base64 encoding is used to convert the encrypted byte[] into a String which will be persisted to the database.

When the persistence provider reads the entity from the database, the method convertToEntityAttribute gets called. It takes the encrypted String from the database, uses a base64 decoding to transform it to a byte[] and performs the decryption. The decrypted String is assigned to the attribute of the entity.

For a real application, you might want to put some more effort into the encryption or move it to a separate class. But this should be good enough explain the general idea.

@Converter
public class CryptoConverter implements AttributeConverter<String, String> {

    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final byte[] KEY = "MySuperSecretKey".getBytes();

    @Override
    public String convertToDatabaseColumn(String ccNumber) {
      // do some encryption
      Key key = new SecretKeySpec(KEY, "AES");
      try {
         Cipher c = Cipher.getInstance(ALGORITHM);
         c.init(Cipher.ENCRYPT_MODE, key);
         return Base64.encodeBytes(c.doFinal(ccNumber.getBytes()));
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
    }

    @Override
    public String convertToEntityAttribute(String dbData) {
      // do some decryption
      Key key = new SecretKeySpec(KEY, "AES");
      try {
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.DECRYPT_MODE, key);
        return new String(c.doFinal(Base64.decode(dbData)));
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
}

OK, we have a type converter that encrypts and decrypts a String. Now we need to tell hibernate to use this converter to persist the ccNumber attribute of the CreditCard entity. As described in one of my previous articles, we could use the @Convert annotation for this. But that would change the code of our application.

Another and for our requirements the better option is to assign the converter in the XML configuration. This can be done in the orm.xml file. The following snippet assigns the CryptoConverter to the ccNumber attribute of the CreditCard entity.

<entity-mappings version="2.1"
        xmlns="http://xmlns.jcp.org/xml/ns/persistence/orm"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence/orm_2_1.xsd">

    <entity class="blog.thoughts.on.java.jpa21.enc.entity.CreditCard">
        <convert converter="blog.thoughts.on.java.jpa21.enc.converter.CryptoConverter" attribute-name="ccNumber"/>
    </entity>
</entity-mappings>

That is everything we need to do to implement and configure a type converter based encryption for a single database field.

Entity Listeners or Type Converter?

The answer for this question is not as easy as it seems. Both solutions have their advantages and disadvantages.

The entity listener described by Bear Giles can use multiple attributes of the entity during encryption. So you can join multiple attributes, encrypt them and store the encrypted data in one database field. Or you can use different attributes for the encrypted and decrypted data to avoid the serialization of the decrypted data (as described by Bear Giles). But using an entity listener has also drawbacks. Its implementation is specific for an entity and more complex than the implementation of a type converter. And if you need to encrypt an additional attribute, you need to change the implementation.

As you saw in the example above, the implementation of a type converter is easy and reusable. The CryptoConverter can be used to encrypt any String attribute of any entity. And by using the XML based configuration to register the converter to the entity attribute, it requires no change in the source code of the application. You could even add it to the application at a later point in time, if you migrate the existing data. A drawback of this solution is, that the encrypted entity attribute cannot be marked as transient. This might result in vulnerabilities if the entity gets written to the disk.

You see, both approaches have their pros and cons. You have to decide which advantages and disadvantages are more important to you.

Conclusion

In the beginning of this post, we defined 3 requirements:

  • provide a transparent encryption that does not affect the application,
  • be able to add the encryption at deployment time,
  • develop application and security/encryption by two different teams/persons.

The described implementation of the CryptoConverter fulfills all of them. The encryption can be added at deployment time and does not affect the application, if the XML configuration is used to assign the type converter. The development of the application and the encryption is completely independent and can be done by different teams. On top of this, the CryptoConverter can be used to convert any String attribute of any entity. So it has a high reusability. But this solution has also some drawbacks as we saw in the last paragraph.

You have to make the decision which approach you want to use. Please write me a comment about your choice.

Thorben Janssen

Thorben Janssen is a senior developer with more than 10 years of experience in Java EE development and architecture. During these years he acted as developer, architect, project and/or technical lead to create high available, clustered mobile billing solutions and laboratory information management systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button