'Generate secure random number with SecureRandom
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
Solution 1:[1]
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?
Solution 2:[2]
This will create a string of 6 random digits.
SecureRandom test = new SecureRandom();
int result = test.nextInt(1000000);
String resultStr = result + "";
if (resultStr.length() != 6)
for (int x = resultStr.length(); x < 6; x++) resultStr = "0" + resultStr;
System.out.println(resultStr); // prints the 6 digit number
Should work quite nicely. Tested so that it would spit out 1000 numbers and all of them were 6 digits long including leading zeros for when the random number initially chosen was less than 100,000.
Solution 3:[3]
You can do something like this:
static String generate(int len){
SecureRandom sr = new SecureRandom();
String result = (sr.nextInt(9)+1) +"";
for(int i=0; i<len-2; i++) result += sr.nextInt(10);
result += (sr.nextInt(9)+1);
return result;
}
Test:
public static void main(String[] argv){
for(int i=3; i<25; i++) System.out.println(generate(i));
}
Output:
639
1617
84489
440757
9982141
28220183
734679206
1501896787
29547455245
417101844095
9997440470982
24273208689568
235051176494856
9515304245005008
73519153118911442
665598930463570609
9030671114119582966
96572353350467673335
450430466373510518561
9664395407658562145827
26651025927755496179441
421157180102739403860678
Solution 4:[4]
This worked for me.
new SecureRandom().nextBytes(values);
int number = Math.abs(ByteBuffer.wrap(values).getInt());
while (number >= 1000000) {
number /= 10;
}
Solution 5:[5]
This is how you would do it using Java IntStream
private final SecureRandom secureRandom = new SecureRandom();
public String generateCode() {
return IntStream.iterate(0, i -> secureRandom.nextInt(10))
.limit(6)
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString();
}
Solution 6:[6]
Maybe using this code?
String.format("%06d", secureRandom.nextInt(999999));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Yahya |
| Solution 3 | |
| Solution 4 | Yahya |
| Solution 5 | Ernest |
| Solution 6 | Kevin D |
