我正在嘗試訪問存盤在 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。
希望我很清楚。提前致謝
uj5u.com熱心網友回復:
類是在設定屬性之前創建的!
您應該將其添加到建構式中:
private final String SECRET;
private final Key key;
private final Cipher cipher;
public AttributeEncryptor(@Value("${datasource.encryptkey}") String secret) throws Exception {
SECRET = secret;
key = new SecretKeySpec(SECRET.getBytes(), AES);
cipher = Cipher.getInstance(AES);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/417591.html
標籤:
