我们正在使用prePersist()(使用 Morphia)和在实体的 getter 中透明地加密/解密我们的一些数据库属性。为了使实体保持整洁,我们使用静态方法。它看起来像这样:
@Override
@PrePersist
public void prePersist() {
    super.prePersist();
    if(password != null){
        if(passwordEncrypted == null){
            passwordEncrypted = new EncryptedString();
        }
        passwordEncrypted.setEncryptedAttribute(AESEncryptor.encrypt(password, passwordEncrypted.getSalt()));
    }
}
请注意,我们没有在该postLoad()方法中解密,因为加密属性并不总是需要,我们希望避免性能开销。不幸的是,这排除了@EntityListener,如http://invariantproperties.com/2012/11/25/database-encryption-using-jpa-listeners/中所述。
public String getPassword() {
    if((password == null) && (passwordEncrypted != null)){
        password = AESEncryptor.decrypt(passwordEncrypted.getEncryptedAttribute(), passwordEncrypted.getSalt());
    }
    return password;
}
现在我们想将加密密码保存在我们的属性文件中,并且应该加载来自正确配置文件(prod、stage、dev)的密码。
加密代码看起来像这样 -getPassword应该通过 Spring 加载:
public static String encrypt(String input, String salt) {
    TextEncryptor encryptor = Encryptors.text(getPassword(), salt);
    String cipher = null;
    try {
        cipher = encryptor.encrypt(input);
    } catch(Exception e){
        LOG.error("Could not encrypt the input '{}', be sure to check the password for illegal characters", input);
    }
    return cipher;
}
虽然可以使用 Spring 加载静态变量(例如http://www.connorgarvey.com/blog/?p=105),但这种做法非常老套,几乎总是不鼓励使用。此外,我们不确定这是否会引发垃圾收集问题。
如何/应该正确完成?