JAVA

[소스코드 보안 취약점]적절하지 않은 난수 값 사용

91cm 2018. 10. 21. 23:12


BAD

1
2
3
4
5
6
7
8
9
10
11
package test;
 
public class Test 
{
 
    public static void main(String[] args) 
{    
        int random= (int) (Math.random()*10); //0~10
        System.out.println(random);
    }
}
cs



Math.random()이 안전하지 않은 이유


=> seed 값이 없기 때문에 난수가 전체적으로 고르게 분포하지않음.





GOOD

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
import java.util.Date;
import java.util.Random;
 
 
public class Test 
{
 
    public static void main(String[] args) 
    {
        
        Random random = new Random();
        random.setSeed(new Date().getTime());
        
        for(int i=0; i<10000;i++)
        {
            System.out.println( (int)(random.nextInt(100))); //0~100
        }
    }
}
cs