Created
April 19, 2015 03:40
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
public class CreditCard { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Integer id; | |
private String ccNumber; | |
private String name; | |
... | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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