【发布时间】:2022-01-20 19:10:59
【问题描述】:
我正在尝试访问存储在 application.properties 中的加密密钥,并将其设置为我的 AttributeEncryptor 中的 SECRET 属性。
这是课程:
package com.nimesia.sweetvillas.encryptors;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.spec.SecretKeySpec;
import javax.persistence.AttributeConverter;
import java.security.InvalidKeyException;
import java.security.Key;
import java.util.Base64;
@Component
public class AttributeEncryptor implements AttributeConverter<String, String> {
private static final String AES = "AES";
@Value("${datasource.encryptkey}")
private String SECRET;
private final Key key;
private final Cipher cipher;
public AttributeEncryptor() throws Exception {
key = new SecretKeySpec(SECRET.getBytes(), AES);
cipher = Cipher.getInstance(AES);
}
@Override
public String convertToDatabaseColumn(String attribute) {
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
return Base64.getEncoder().encodeToString(cipher.doFinal(attribute.getBytes()));
} catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) {
throw new IllegalStateException(e);
}
}
@Override
public String convertToEntityAttribute(String dbData) {
try {
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(Base64.getDecoder().decode(dbData)));
} catch (InvalidKeyException | BadPaddingException | IllegalBlockSizeException e) {
throw new IllegalStateException(e);
}
}
}
datasource.encryptkey 在 application.properties 中。 我试图从控制器访问它并且它有效。但是当我在这里尝试使用它时,它给了我一个 NullPointerException。
希望我很清楚。 提前致谢
【问题讨论】:
标签: java spring spring-boot