[Jasypt] Spring Boot yaml 파일 암호화

2023. 10. 16. 23:25·Spring
728x90

 

Jasypt
Java Simplified Encryption의 약자로, 자바로 간단히 암호화할 수 있게 도와주는 라이브러리

 

파일트리
├ src
 │ └─ main
 │   │   ├─ JasyptConfig.kt
 │   │   └─ KotlinStudyApplication.kt
 │ └─ resources
 │      ├─ application.yml
 │      └─ jasypt-encryptor-password.txt
└─ .gitignore

 

1. build.gradle에 jasypt-spring-boot-starter 추가

dependencies {
    implementation ("com.github.ulisesbocchio:jasypt-spring-boot-starter:3.0.3")
    ... 생략
}

 

2. yaml 파일에 Jasypt 설정 정보 추가

# Jasypt
jasypt: 
  encryptor:
    bean: jasyptStringEncryptor # Jasypt Config 파일에서 등록하는 빈의 이름
    algorithm: PBEWithMD5AndDES # 암/복호화에 사용되는 알고리즘
    pool-size: 2 # 암호화 요청을 담고 있는 pool의 크기
    string-output-type: base64 # 암호화 이후에 어떤 형태로 값을 받을지 설정. base64 / hexadecimal을 선택
    key-obtention-iterations: 100000 # 암호화 키를 얻기 위해 반복해야 하는 해시 횟수

 

3. jasypt-encryptor-password 파일 생성

# 패스워드 설정

 

4.Jasypt Config 파일 생성

@Configuration
@EnableEncryptableProperties
class JasyptConfig {
    @Value("\${jasypt.encryptor.algorithm}")
    private val algorithm: String? = null

    @Value("\${jasypt.encryptor.pool-size}")
    private val poolSize = 0

    @Value("\${jasypt.encryptor.string-output-type}")
    private val stringOutputType: String? = null

    @Value("\${jasypt.encryptor.key-obtention-iterations}")
    private val keyObtentionIterations = 0

    val log = LoggerFactory.getLogger(javaClass)


    @Bean
    fun jasyptStringEncryptor(): StringEncryptor {
        val encryptor = PooledPBEStringEncryptor()
        encryptor.setPoolSize(poolSize)
        encryptor.setAlgorithm(algorithm)
        encryptor.setPassword(jasyptEncryptorPassword)
        encryptor.setStringOutputType(stringOutputType)
        encryptor.setKeyObtentionIterations(keyObtentionIterations)

        val source = "변환할 데이터"
        log.info("plane :: {}, encrypt :: {}", source, encryptor.encrypt(source))

        return encryptor
    }

    private val jasyptEncryptorPassword: String
        private get() = try {
            val resource = ClassPathResource("jasypt-encryptor-password.txt")
            Files.readAllLines(Paths.get(resource.uri)).stream().collect(Collectors.joining(""))
        } catch (e: IOException) {
            throw RuntimeException("Not found Jasypt password file.")
        }
}

 

5. 변환한 데이터를 yml 파일에 적용

spring:
  datasource:
      driver-class-name: org.mariadb.jdbc.Driver
      url: jdbc:mariadb:
      username:
      password: ENC([암호화값])

 

 6. jasypt-encryptor-password 파일 .gitignore에 추가

/src/main/resources/jasypt-encryptor-password.txt

 

 

더보기

참고

https://bbubbush.tistory.com/46

 

[개발 Tip] Yaml, Properties 안에 중요한 정보를 암호화하기 feat. Jasypt 사용 방법

들어가며 며칠 전, Github에 토이 프로젝트 소스를 올렸더니, GitGuardian에서 *.yaml 파일에 계정 정보가 들어가 있다고 알려주었다. 단순히 파일만 삭제하고 커밋하면 git log를 통해 다시 확인할 수 있

bbubbush.tistory.com

https://velog.io/@haeny01/Jasypt-yaml-%ED%8C%8C%EC%9D%BC%EC%9D%98-%EC%95%94%ED%98%B8%ED%99%94

 

[Jasypt] yaml 파일의 암호화

SpringBoot 프로젝트 yaml 파일 내 특정문자열 암호화

velog.io

728x90
'Spring' 카테고리의 다른 글
  • Spring @Async 비동기 처리
  • Spring websocket 웹소켓, java 채팅 프로그램
  • Spring AOP, 관점 지향 프로그래밍
  • @Component, @Bean 어노테이션
Karla Ko
Karla Ko
𝘾𝙤𝙣𝙩𝙞𝙣𝙪𝙤𝙪𝙨𝙡𝙮 𝙄𝙢𝙥𝙧𝙤𝙫𝙞𝙣𝙜, 𝘾𝙤𝙣𝙨𝙩𝙖𝙣𝙩𝙡𝙮 𝘿𝙚𝙫𝙚𝙡𝙤𝙥𝙞𝙣𝙜 𝙔𝙚𝙨!
    250x250
  • Karla Ko
    karlaLog
    Karla Ko
  • 전체
    오늘
    어제
    • Total (467)
      • Spring (19)
      • JPA (4)
      • Cloud & Architecture (15)
        • Kubernetes (5)
        • Docker (3)
        • MSA (2)
        • GCP (1)
        • AWS (4)
      • Devops (1)
      • Message Queue (4)
        • Kafka (2)
        • RabbitMQ (2)
      • Git (4)
      • DB (4)
      • Java (9)
      • Python (4)
      • CS (11)
        • OS (8)
        • Network (2)
        • Algorithm (1)
      • Coding Test (392)
        • programmers (156)
        • Graph (43)
        • DP (37)
        • Search (31)
        • Tree (13)
        • Data Structure (26)
        • Combination (12)
        • Implement (18)
        • Geedy (23)
        • Sort (7)
        • Math (21)
        • geometry (2)
  • 블로그 메뉴

    • 홈
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    LIS
    Algorithm
    힙
    스택
    동적계획법
    월간코드챌린지
    DFS
    정렬
    DP
    파이썬
    BFS
    플로이드워셜
    조합
    그래프
    그리디
    재귀
    덱
    최소신장트리
    구현
    다익스트라
    큐
    알고리즘
    최대공약수
    구간합
    트리
    자료구조
    프로그래머스
    이분탐색
    백준
    최단거리
  • hELLO· Designed By정상우.v4.10.3
Karla Ko
[Jasypt] Spring Boot yaml 파일 암호화
상단으로

티스토리툴바