I am building an application that persists patient data. In order for the data to remain searchable, the identifiers and names need to be left un-encrypted(?). However I am planning to encrypt all other fields like address, phone, email, family members details and so on. I am using an AttributeConverter for this:
@Converter
public class AttributeEncryptor implements AttributeConverter<String, String> {
private static final String AES = "AES";
private static final byte[] encryptionKey = "big-secret".getBytes();
private final Cipher encryptCipher;
private final Cipher decryptCipher;
public AttributeEncryptor() throws Exception {
Key key = new SecretKeySpec(encryptionKey, AES);
encryptCipher = Cipher.getInstance(AES);
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
decryptCipher = Cipher.getInstance(AES);
decryptCipher.init(Cipher.DECRYPT_MODE, key);
}
@Override
public String convertToDatabaseColumn(String attribute) {
try {
return Base64.getEncoder().encodeToString(encryptCipher.doFinal(attribute.getBytes()));
} catch (IllegalBlockSizeException | BadPaddingException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public String convertToEntityAttribute(String dbData) {
try {
return new String(decryptCipher.doFinal(Base64.getDecoder().decode(dbData)));
} catch (IllegalBlockSizeException | BadPaddingException e) {
throw new IllegalArgumentException(e);
}
}
}
Is this the best approach? Are there other preferred / alternative options?