我正在构建一个保存患者数据的应用程序。为了使数据保持可搜索性,标识符和名称需要保持未加密(?)。然而,我计划加密所有其他字段,如地址,电话,电子邮件,家庭成员的详细信息等。我使用AttributeConverter:
@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);
}
}
}
这是最好的方法吗?是否有其他首选/替代方案?
这是我看到的一篇很好的文章,讨论了各种选择和它们的利弊。https://stackoverflow.com/a/43779197/5417843