I am trying to access my encrypt key stored in application.properties and set it as SECRET property in my AttributeEncryptor.
This is the class:
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 is in application.properties. I have tried to access it from a controller and it worked. But when I try and use it in here it gives me a NullPointerException.
Hope I was clear. Thanks in advance
CodePudding user response:
The class is created before the property is set!
You should add it to the constructor instead:
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);
}