BCrypt

[Spring] BCrypt이용 해서 Security없이 암호화 하기
Feb 21, 2024
BCrypt
💡
security 없이 암호화 하기(단방향은 다 HASH) → 복호화 불가능

라이브러리 설치

// https://mvnrepository.com/artifact/org.mindrot/jbcrypt implementation group: 'org.mindrot', name: 'jbcrypt', version: '0.4'

회원가입

코드 작성

notion image

테스트 코드 작성

notion image
salt 오류 발생 다시 테스트
notion image
notion image

코드 수정

@PostMapping("/join") public String join(UserRequest.JoinDTO requestDTO) { // @ResponseBody를 적으면 파일을 반환하는것이 아니라 메시지를 반환한다. System.out.println(requestDTO); String rawPassword = requestDTO.getPassword(); String encPassword = BCrypt.hashpw(rawPassword,BCrypt.gensalt()); requestDTO.setPassword(encPassword); // 1. 유효성 검사 if (requestDTO.getUsername().length() < 3) { return "error/400"; } // 2.동일 username 체크 (나중에 하나의 트랜잭션으로 묶는게 좋다.) User user = userRepository.findByUsername(requestDTO.getUsername()); try{ userRepository.save(requestDTO); }catch (Exception e){ throw new RuntimeException("아이디가 중복되었어요"); } return "redirect:/loginForm"; }

더미 데이터 수정

insert into user_tb(username, password, email, created_at) values('ssar', '$2a$10$NU03go6lJRh9RRUHvmrjwuAKOJsG6/Q/scvGtOwPOu7TDUbqnP2oK', 'ssar@nate.com', now()); insert into user_tb(username, password, email, created_at) values('cos', '$2a$10$NU03go6lJRh9RRUHvmrjwuAKOJsG6/Q/scvGtOwPOu7TDUbqnP2oK', 'cos@nate.com', now());
로그인시에는 암호화를 하지 않기 때문에 로그인은 아직 불가능

로그인

💡
암호화 되기전 패스워드를 암호화하면 매번 다른 값이 나옴 BCrypt.checkpw(로그인패스워드, 데이터베이스에 있는 패스워드) → 비교해주는 메서드 제공
notion image
notion image

코드 작성

암호화 돼었기 때문에 Password로 조회 불가능 하므로 코드 수정
notion image
findByUsername
notion image
검증 실패시 코드 작성
notion image

정상 작동 확인하기

회원가입

notion image
notion image
 
 
Share article
RSSPowered by inblog