JHLBLUE
Springframework security의 BCryptPasswordEncoder 사용하기 본문
전자정부프레임워크 3.7(Spring framework 4.2.4) 기준 사용예시입니다.
데이터베이스에 비밀번호를 저장할 떄에는 sha256 등의 안전한 알고리즘을 사용하여 사용자의 비밀번호를 해시 데이터로 만들어 두는것이 좋다.
하지만 salt가 포함되지 않은 패스워드 생성함수를 사용할 경우 같은 비밀번호에 대해 동일한 해시 데이터가 만들어지기 때문에 위험하다.
위의 password는 문자열 "password"를 자바의 DigestUtils.sha512Hex() 함수를 이용하여 해시 데이터를 만든 값으로, salt가 없기 때문에 동일한 값이 생성되는 것이다.
이런 문제를 해결하기 위해 Springframework Security의 BCryptPasswordEncoder를 사용하는 것이다.
Springframework의 BCryptPasswordEncoder은 BCrypt 해시 함수를 이용하여 비밀번호를 저장하는 방법을 사용한다
BCryptPasswordEncoder의 생성자 호출 시 strength를 설정할 수 있으며, 이는 round 값을 설정하는 부분이다.
BCryptPasswordEncoder 객체에서 사용 가능한 메소드는 encode, matches로, 각각 평문 해시화 기능과 해시결과 일치여부 확인 기능을 제공한다.
1. pom.xml 파일에 springframework.security dependency 추가하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>4.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>4.2.4.RELEASE</version> </dependency> | cs |
2019년 1월 기준으로 springframework security는 5.1.3.RELEASE가 최신버전이지만 Springframework 4.2버전과 호환이 되지 않으며, 5.x 버전을 사용할 경우 아래와 같은 에러가 발생한다.
2. 테스트 코드 및 결과 확인
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder(10); String returnValue1 = bcryptPasswordEncoder.encode("password"); String returnValue2 = bcryptPasswordEncoder.encode("password"); String returnValue3 = bcryptPasswordEncoder.encode("password"); System.out.println("returnValue1 : " + returnValue1); System.out.println("returnValue2 : " + returnValue2); System.out.println("returnValue3 : " + returnValue3); System.out.println("============================================================================"); System.out.println("matches() result : " + bcryptPasswordEncoder.matches("password", returnValue1)); System.out.println("matches() result : " + bcryptPasswordEncoder.matches("password", returnValue2)); System.out.println("matches() result : " + bcryptPasswordEncoder.matches("password", returnValue3)); | cs |
BCryptPasswordEncoder 생성자 호출시 넣을 수 있는 strength의 값은 4부터 31까지 넣을 수 있지만 지나치게 높은 값을 넣을 경우 해시 작업이 매우 오래 걸릴 수 있기 때문에 적절한 값을 넣는 것이 좋다.
이전에 StandardPasswordEncoder를 사용하여 비밀번호를 해시화하여 저장했지만 해당 클래스는 4.2.6.RELEASE 버전부터 deprecated되었기 때문에 사용하지 않는 것이 좋다.
아래는 StandardPasswordEncoder를 사용하여 문자열 password를 저장한 값이다.
'개발 > 전자정부프레임워크' 카테고리의 다른 글
서버로부터 메시지 받아서 팝업 띄우기 (2. AJAX 이용) (0) | 2017.11.27 |
---|---|
서버로부터 메시지 받아서 팝업 띄우기 (1. ModelAndView 이용) (0) | 2017.11.14 |
이클립스에 전자정부 프레임워크 플러그인 설치 (0) | 2017.11.14 |
ExcelUtil (0) | 2017.11.13 |