본문 바로가기

Java/Spring

Spring - Jasypt 예제

스프링에서 Jasypt 를 사용해보도록 하겠습니다. 


http://www.jasypt.org/

Jasypt is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.

maven

저는 스프링 4.x 을 쓰기 때문에 jasypt-spring31 을 가져옵니다. 
maven repository에 가면 jasypt-spring3 도 있는데 이건 스프링 3.0 까지의 버전에서 사용한다고 합니다. 

<!-- https://mvnrepository.com/artifact/org.jasypt/jasypt-spring31 -->
<dependency>
    <groupId>org.jasypt</groupId>
    <artifactId>jasypt-spring31</artifactId>
    <version>1.9.2</version>
</dependency>
cs

bean 설정

스프링 설정파일로 가서 아래와 같이 설정해 줍니다. 


  1. 암호화와 복호화에 사용할 키를 넣으시면 됩니다.
  2. 데이터베이스 접속정보가 들어있는 properties 경로를 넣으시면 됩니다.
<!-- Jasypt 설정 -->
<bean id="encryptorConfig" class="org.jasypt.encryption.pbe.config.EnvironmentPBEConfig">  
       <property name="algorithm" value="PBEWithMD5AndDES" />  
       <!-- 1 -->
       <property name="password" value="암호화 키" />
</bean>  
 
<bean id="encryptor" class="org.jasypt.encryption.pbe.StandardPBEStringEncryptor">  
       <property name="config" ref="encryptorConfig" />  
</bean>  
 
<bean class="org.jasypt.spring31.properties.EncryptablePropertyPlaceholderConfigurer">
    <constructor-arg ref="encryptor" />
        <property name="locations">
            <list>
                <!-- 2 -->
                <value>classpath:/conf/db.properties.xml</value>
            </list>
     </property>
</bean>
cs

암호화

http://www.jasypt.org/download.html 로 가서 Jasypt 를 다운로드 받고 압축을 풉니다. 

해당 폴더의 /bin 으로 들어가 cmd 를 열고 아래와 같이 입력합니다. 


encrypt input="암호화할 값" password="암호화 키" algorithm="PBEWITHMD5ANDDES"
cs


위의 algorithm 값은 bean을 만들 때 입력했던 <property name="algorithm" value="......" /> 부분과 동일해야 합니다.

사용가능한 알고리즘은 아래와 같다고 나와있네요.

DIGEST ALGORITHMS: [MD2, MD5, SHA, SHA-256, SHA-384, SHA-512] PBE ALGORITHMS: [PBEWITHMD5ANDDES, PBEWITHMD5ANDTRIPLEDES, PBEWITHSHA1ANDDESEDE, PBEWITHSHA1ANDRC2_40]


그럼 아래와 같이 암호화가 완료된 output이 나옵니다.


다운받고 하는 과정이 번거로우시면 아래와 같이 테스트코드 작성해서 구하시면 되겠습니다. 

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import lombok.extern.slf4j.Slf4j;
 
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
@Slf4j
public class JasyptTests {
    
    @Test
    public void jastypt() {
        StandardPBEStringEncryptor pbeEnc = new StandardPBEStringEncryptor();
        
        pbeEnc.setAlgorithm("PBEWithMD5AndDES");
        pbeEnc.setPassword("pw_key");
 
        String password = pbeEnc.encrypt("test");
        
        log.info(password);
    }
    
}
cs

properties 수정

기존의 값을 제거하고 ENC(암호화 값) 으로 변경합니다. 

<entry key="db.password">ENC(9Y3AuCE3fP6qpG43auIrHA==)</entry>
cs

dataSource 수정

properties를 읽어서 값을 가져올 때 # 과 $ 방식이 있는데,

파일마다 id를 부여하고 # 을 사용하는 것이 더 명확하다고 생각하여 사용중이었습니다만 

Jasypt를 사용하면 $ 방식을 사용해야 합니다. 

<!-- db.properties.xml -->
<util:properties id="config" location="classpath:/conf/db.properties.xml" />
 
<!-- Root Context: defines shared resources visible to all other web components -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
    <property name="driverClassName" value="#{config['db.driverClassName']}" />
    <property name="jdbcUrl" value="#{config['db.jdbcUrl']}" />
    <!-- Jasypt 쓰려면 ${} 방식으로 읽어야 함. -->
    <property name="username" value="${db.username}" />
    <property name="password" value="${db.password}" />
</bean>
cs


변경을 마치고 데이터베이스 연결 테스트를 통과한 것을 확인할 수 있습니다.