1

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?

skyman
  • 2,255
  • 4
  • 32
  • 55

1 Answers1

0

This is a good post I came across, discussing various options and their Pros/ Cons. https://stackoverflow.com/a/43779197/5417843

shri_world
  • 36
  • 5