Spring

Spring Boot jasypt를 통한 Credentials 암호화

kimc 2022. 11. 5. 20:01
반응형

 

스프링 jasypt를 통한 키값 기본 보안 세팅 (코틀린)

 


 

이번 글을 통해 배워 갈 내용

  1. Jasypt로 중요 비밀번호, 키값, credential, application.yml 혹은 properties 암호화

먼저 Depency를 추가합니다

 

기본 jasypt를 사용하는 방법도 있겠지만

세팅의 편의를 위해서

Jasypt Spring Boot Starter를 사용하였습니다

 

보안 관련해서 최신 버전을 아래에서 확인 후 세팅하시길 바랍니다

https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter

 

기본 버전을 사용하시고자 하시는 분들은 아래 참조

https://mvnrepository.com/artifact/org.jasypt/jasypt

 

저는 코틀린 gradle이어서 아래와 같이 세팅했습니다

// https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter
implementation("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.4")

세팅방법은 크게 4가지가 있습니다

저는 가장 간단한 방법으로 진행하겠습니다

제 방법은 @SpringBootApplication이나 @EnableAutoConfiguration을 사용하시는 분들이 많이 쓰시는 방법입니다

다른 방법을 쓰시고자 하시는 분들은 아래 링크를 참조해주시기 바랍니다

https://github.com/ulisesbocchio/jasypt-spring-boot

 

GitHub - ulisesbocchio/jasypt-spring-boot: Jasypt integration for Spring boot

Jasypt integration for Spring boot. Contribute to ulisesbocchio/jasypt-spring-boot development by creating an account on GitHub.

github.com


일단 샘플용으로 아래와 같이 만들었습니다

application.properties 파일에 아래와 같이 추가하였고

example.properties=codemasterkimc

data loader에서 불러옵니다

코틀린 코드이나 필요시 자바로 변경해서 써주시면 됩니다

import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.CommandLineRunner
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component

@Order(1)
@Component
class DataLoader(
    @Value("\${example.properties}")
    private val test: String
) : CommandLineRunner {
    override fun run(vararg args: String) {
        println(">>> $test")
    }
}

앱을 실행하면 코드마스터 김씨가 출력됩니다


jasypt 동작원리는

Spring 환경에 포함된 모든 Property Source와 작용하는 Spring Post Process를 등록해서 "암호화를 인식" 하게 합니다

따라서 jasypt property convetion을 따르게 됩니다.


Spring 환경에 포함된 모든 PropertySource 객체를 장식하는 Spring 포스트 프로세서를 등록하여 "암호화를 인식"하고 jasypt의 속성 규칙에 따라 속성이 암호화될 때 감지합니다.
일반 속성, 시스템 속성 또는 명령줄 인수를 통해 구성할 수 있는 기본 StringEncryptor를 정의합니다.


실습을 해보겠습니다

MVN 이나 GRADLE Command로 암호화 및 복호화하는 게 더 좋지만

편의를 위해서 아래 링크를 사용하겠습니다.

https://www.devglan.com/online-tools/jasypt-online-encryption-decryption

 

Programming Blog Article Feeds as per your Interest | DevGlan

Best programming article feeds as per your Interest on different technologies. Subscribe to any technology and explore the best articles from around the web.

www.devglan.com

 

암호화할 값은 codemasterkimc

암호화할 키값은 CODEMASTERKIMCMADETHISTEMPORARYPASSOWRD

그리고 암호화 된 값은 J/W4vE7Csvl+I2ReTKg+unpVcTni4eIh 입니다

아까 작성한 application.properties에 아래 값을 넣어줍니다

example.properties=ENC(J/W4vE7Csvl+I2ReTKg+unpVcTni4eIh)

그리고 JasyptConfig 파일을 만듭니다

편의를 위해서 공식 깃을 참고해서 만들었지만

보안의 경우 알고리즘이나 세팅을 바꾸고

mvn이나 gradle 커맨드로 암호화 및 복호화하는 것을 추천드립니다

import org.jasypt.encryption.StringEncryptor
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration


@Configuration
class JasyptConfig(
    @Value("\${jasypt.encryptor.password}")
    private val password: String
) {
    @Bean("jasyptStringEncryptor")
    fun stringEncryptor(): StringEncryptor {
        val encryptor = PooledPBEStringEncryptor()
        val config = SimpleStringPBEConfig()
        config.password = password
        config.algorithm = "PBEWITHMD5AndDES"
        config.setKeyObtentionIterations("1000")
        config.setPoolSize("1")
        config.providerName = "SunJCE"
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator")
        config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator")
        config.stringOutputType = "base64"
        encryptor.setConfig(config)
        return encryptor
    }
}

키값은 환경변수로 하셔도 되고 VM option에 주셔도 되는데

Intellij 기준 

Configuration으로 

VM option을 추가하셔서 세팅해주시면 됩니다

-Djasypt.encryptor.password=CODEMASTERKIMCMADETHISTEMPORARYPASSOWRD

 

정상적으로 출력된 것을 확인할 수 있습니다

 


참조 및 인용

https://mvnrepository.com/artifact/org.jasypt/jasypt

 

https://stackoverflow.com/questions/35531661/using-env-variable-in-spring-boots-application-properties

 

Using env variable in Spring Boot's application.properties

We are working on a Spring Boot web application, and the database we are using is MySQL; the setup we have is we first test it locally (means we need to install MySQL on our PC); then we push to

stackoverflow.com

https://github.com/ulisesbocchio/jasypt-spring-boot

 

GitHub - ulisesbocchio/jasypt-spring-boot: Jasypt integration for Spring boot

Jasypt integration for Spring boot. Contribute to ulisesbocchio/jasypt-spring-boot development by creating an account on GitHub.

github.com

https://www.devglan.com/online-tools/jasypt-online-encryption-decryption

 

Programming Blog Article Feeds as per your Interest | DevGlan

Best programming article feeds as per your Interest on different technologies. Subscribe to any technology and explore the best articles from around the web.

www.devglan.com

http://www.jasypt.org/encrypting-configuration.html

 

Jasypt: Java simplified encryption - Jasypt: Java simplified encryption - Encrypting application configuration files

This guide contains low-level technical information. Maybe you should start first with the Easy Usage or General Usage guides? Encrypting application configuration files Jasypt offers support for encrypted application configuration in three different ways:

www.jasypt.org

 

반응형