본문 바로가기
Back-end/JAVA & Spring

[java] 임시 비밀번호 생성 Random / SecureRandom /RandomStringUtils)

by 꼬바리 2022. 3. 3.

java.util.Random 클래스는 난수를 생성할 때 seed값으로 시간을 이용합니다.

그래서 동일한 시간에 Random 클래스를 사용하여 난수를 사용하면 동일한 값이 리턴됩니다.

예측 가능한 난수를 사용하는 경우 공격자가 SW에서 생성되는 다음 숫자를 예상하여 시스템을 공격할 수 있습니다.

 

시큐어코딩 가이드 - SW 보안약점 47개 항목 중 적절하지 않은 난수 값 사용 (Use of Insufficiently Random Values)에 해당됩니다.

반면에 java.security.SecureRandom 클래스는 예측할 수 없는 seed를 이용하여 강력한 난수를 생성합니다.

 

임시 비밀번호 생성

 

getRamdomPassword(10)를 호출하면 10 글자의 임시비밀번호가 생성됩니다.

import java.security.SecureRandom;
import java.util.Date;

//...

    public String getRamdomPassword(int size) {
        char[] charSet = new char[] {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                '!', '@', '#', '$', '%', '^', '&' };

        StringBuffer sb = new StringBuffer();
        SecureRandom sr = new SecureRandom();
        sr.setSeed(new Date().getTime());

        int idx = 0;
        int len = charSet.length;
        for (int i=0; i<size; i++) {
            // idx = (int) (len * Math.random());
            idx = sr.nextInt(len);    // 강력한 난수를 발생시키기 위해 SecureRandom을 사용한다.
            sb.append(charSet[idx]);
        }

        return sb.toString();
    }

 

 

RandomStringUtils의 randomAlphanumeric메소드를 호출하면 알파벳(대소문자)+숫자 랜덤 값을 얻을 수 있습니다.

import org.apache.commons.lang3.RandomStringUtils;

...
    public String getRamdomPassword(int size) {
        RandomStringUtils.randomAlphanumeric(size);
    }

 

RandomStringUtils

  • random(int count) : 임의의 문자를 count만큼 랜덤으로 생성.
  • random(int count, boolean letters, boolean numbers) : letters값이 true면 문자만 사용. numbers값이 true면 숫자만 사용. 둘다 true면 문자와 숫자만 사용
  • random(int count, int start, int end, boolean letters, boolean numbers) : 아스키코드 번호 start부터 end까지의 문자를 count만큼 랜덤으로 생성.
  • randomAlphabetic(int count) : 영문 대소문자를 count만큼 랜덤으로 생성.
  • randomNumeric(int count) : 숫자를 count만큼 랜덤으로 생성.
  • randomAlphanumeric(int count) : 대소문자, 숫자를 count만큼 랜덤으로 생성.
  • randomAscii(int count) : 아스키코드 32("") 부터 126(-) 사이의 코드를 count만큼 랜덤으로 생성.

 



728x90

댓글