Skip to content

Instantly share code, notes, and snippets.

@thjanssen
Created April 19, 2015 03:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thjanssen/03c652cf0108b31f86d1 to your computer and use it in GitHub Desktop.
Save thjanssen/03c652cf0108b31f86d1 to your computer and use it in GitHub Desktop.
How to use a JPA Attribute Converter to encrypt your data (http://www.thoughts-on-java.org/2014/06/how-to-use-jpa-type-converter-to.html)
@Entity
public class CreditCard {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String ccNumber;
private String name;
...
}
@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);
}
}
}
<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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment