I am currently using jpa attribute converter to encrypt some of the db fields. However, I have a requirement to separate the encrypt keys based on the other field on the entity.
for example, I would like to use key 123456
to encrypt the field name
if org
field is external
, and use key qwert
to encrypt field name
if org
field is internal
.
JPA attribute does not have access to the entity's other field, so I have to find workarounds.
So is it possible to do this?
Thanks
Provide one solution for your scenario , one way to do this is by handling the encryption logic within itself ,or callback listener method to apply encryption key before persisted or updated;
@Entity
@EntityListeners(MyEntityListener.class)
public class MyEntity {
@Id
private Long id;
private String org; // "external" or "internal"
private String name; // The name that will be encrypted in the DB
// getters and setters
}
public class MyEntityListener {
@PrePersist
@PreUpdate
public void encryptName(MyEntity entity) {
String key = getKeyBasedOnOrg(entity.getOrg());
entity.setName(EncryptionUtil.encrypt(entity.getName(), key));
}
@PostLoad
public void decryptName(MyEntity entity) {
String key = getKeyBasedOnOrg(entity.getOrg());
entity.setName(EncryptionUtil.decrypt(entity.getName(), key));
}
private String getKeyBasedOnOrg(String org) {
if ("external".equals(org)) {
return "123456";
} else if ("internal".equals(org)) {
return "qwert";
}
return "defaultKey";
}
}