본문 바로가기
JAVA/기초

[JAVA] BCryptPasswordEncoder 단방향 비밀번호 암호화

by 뿌비 2022. 8. 24.
728x90
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

spring security 사용하여 패스워드 암호화 적용 하기
BCryptPasswordEncoder를 사용하기 위해서 security 설정


1. pom.xml 에 아래의 코드 추가

<!-- spring-security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>	
    </dependency>

2. BoardApplication.java 파일이 있는 경로에 SpringSecurity.java 파일을 만들어준다.

2

3. SpringSecurity.java 파일에 아래의 코드를 넣어준다.

package com.example.board.board;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SpringSecurity extends WebSecurityConfigurerAdapter {
   // WebSecurityConfigurerAdapter 지원종료로 노란줄이 뜨는데 넣어놔도 작동이 됐다

   // 암호화를 하는 service 
    private com.example.board.board.service.boardService boardService;

   // 암호화
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().disable()
                .csrf().disable()
                .formLogin().disable()
                .headers().frameOptions().disable();
    }
}

4. boardService.java 에서 비밀번호 암호화를 하려는 곳에 아래의 코드를 넣어주면 된다.

// 비밀번호 암호화
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
	// values.getPassword() 부분에 암호화하고 싶은 비밀번호를 넣어주면 된다
        String newPassword = encoder.encode(values.getPassword());
        System.out.println("컨트롤러 newPassword ==== " + newPassword)

5. 암호화된 결과

암호화 된 패스워드


security 설정이 제대로 되면 터미널을 실행했을 때 아래의 사진처럼 뜨면서  security 비밀번호가 나온다.

security 설정 후 터미널 실행


https://soobindeveloper8.tistory.com/547 [참고]
https://youngjinmo.github.io/2021/05/passwordencoder/ [참고]
https://hou27.tistory.com/entry/Spring-Boot-Spring-Security-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0-%EC%95%94%ED%98%B8%ED%99%94 [참고]
https://kdg-is.tistory.com/entry/Spring-Spring-security%EC%9D%B4%EC%9A%A9%ED%95%9C-%EB%B9%84%EB%B0%80%EB%B2%88%ED%98%B8-%EC%95%94%ED%98%B8%ED%99%94-%EB%B3%B5%ED%98%B8%ED%99%94 [참고]

 

728x90