의존성 추가
implementation 'com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.5'
Config 추가
@Configuration
public class JasyptConfig {
@Bean
public StringEncryptor stringEncryptor() {
PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
config.setPassword(System.getenv("JASYPT_ENCRYPTOR_KEY"));
config.setPoolSize("1");
config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
config.setStringOutputType("base64");
config.setKeyObtentionIterations("1000");
config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
encryptor.setConfig(config);
return encryptor;
}
}
암복호화 시 사용되는 키를 환경변수에 저장해두어서 그 값을 읽어오기 위해 System.getenv() 메서드를 사용했다.
테스트
@SpringBootTest
@TestPropertySource(locations = "classpath:application.yml")
class JasyptConfigTest{
@Value("${jasypt.encryptor.password}")
private String key;
@Test
public void jasypt_encrypt_test() {
String s3_host_url = "https://heyannyeoung.s3.ap-northeast-2.amazonaws.com/";
System.out.println("encoded value: " + encoding(s3_host_url));
}
private String encoding(String value) {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
encryptor.setPassword(key);
encryptor.setIvGenerator(new RandomIvGenerator());
return encryptor.encrypt(value);
}
}
yml
...
jasypt:
encryptor:
password: ${JASYPT_ENCRYPTOR_KEY}
결과값
encoded value: I32hMXRzx/G6jjZkEhKioXJF8tG/RmXbS+1bvF2tT8cp6cbLEChUFfRB3k4f9rdSPC6..
문제 & 해결
1. 환경변수를 사용하기 위해 yml에서 환경변수를 받아오게 했는데 테스트 패키지에서 이것저것 고쳐보고 껏다키고 해도 yml에 있는 값이 불러와지지가 않았다.
@SpringBootTest와 @TestPropertySource(locations = "classpath:application.yml") 을 둘 다 붙여주니 해결되었다.
2. 테스트 환경에서 인코딩/디코딩이 잘 되는 것을 확인한 후 yml의 파일을 싹 다 바꾸고 실행을 돌렸는데 복호화가 되질 않았다.
...either 'jasypt.encryptor.password', one of ['jasypt.encryptor.private-key-string', 'jasypt.encryptor.private-key-location'] for asymmetric encryption, or one of ['jasypt.encryptor.gcm-secret-key-string', 'jasypt.encryptor.gcm-secret-key-location', 'jasypt.encryptor.gcm-secret-key-password'] for AES/GCM encryption must be provided for Password-based or Asymmetric encryption
...jasypt Update your application's configuration
위와 같은 오류 외에도 이것저것 에러가 발생했는데 쨋든 복호화에 사용될 키가 매칭되지 않아서인 것 같았다.
처음엔 jasypt.encrypt.key라는 키를 yml에 생성한 후 이 값을 config 클래스에서 사용하게 했는데 config 클래스가 키를 못찾아오길래 에러에서 요구하는대로 jasypt.encryptor.password로 바꿔주니 작동이 잘 됐다.
테스트 환경에는 yml에서 불러오게 하고 config 클래스에서는 환경변수에 있는 값을 직접 불러오게 했는데 둘 다 작동이 잘 된다!