Generate secure random number with SecureRandom

MobileAppDeveloper picture MobileAppDeveloper · Jul 21, 2017 · Viewed 11.1k times · Source

How can I generate a 6 digit integer using SecureRandom class of Java?

I am trying the following code to generate random numbers :

SecureRandom secureRandom = new SecureRandom();
int secureNumber = secureRandom.nextInt();

It is generating random numbers with any length including negative number. I don't find any method in SecureRandom class to provide a range of numbers. I want to generate a 6 digits positive random number

Answer

Pfollvosten picture Pfollvosten · Jul 21, 2017

simply done it with an array

int[] arr = new int[6];
Random rand = new SecureRandom();
for(int i= 0; i< 6 ; i++){
    // 0 to 9
    arr[i] = rand.nextInt(10);   
}

Dont know if you need it in another type (if you want int look here: How to convert int array to int?