我正在使用JPA AttributeConverter来加密存储在数据库中的字符串。与提议的内容非常相似: http://www.thoughts-on-java.org/how-to-use-jpa-type-converter-to/
但是,该示例在转换器中创建了密钥:
@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);
}
}
}
我的密钥(以及加密的其他部分)取决于其他状态。此状态不是AttributeConverter接口的一部分,因此无法传入。
存储此(每个请求)状态的最佳方法是什么,以便AttributeConverter可以访问它?
感谢。