I have the below code which uses java.util.Random
, now I want to change to java.security.SecureRandom
. How do I do the same operations with SecurRandom?
int rand = 0;
for (int i = 0; i < 8; i++) {
rand = (int) (Math.random() * 3);
switch (rand) {
case 0:
c = '0' + (int) (Math.random() * 10);
break;
case 1:
c = 'a' + (int) (Math.random() * 26);
break;
case 2:
c = 'A' + (int) (Math.random() * 26);
break;
}
}
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
int rand = 0;
for (int i = 0; i < 8; i++) {
rand = random.nextInt(3);
switch (rand) {
case 0:
c = '0' + random.nextInt(10);
break;
case 1:
c = 'a' + random.nextInt(26);
break;
case 2:
c = 'A' + random.nextInt(26);
break;
}
secureRandomObject.nextDouble()
is essentially equivalent to Math.random()
So following code will work...
SecureRandom secureRandom = new SecureRandom();
int rand = 0;
for (int i = 0; i < 8; i++) {
rand = (int) (secureRandom.nextDouble() * 3);
switch (rand) {
case 0:
c = '0' + (int) (secureRandom.nextDouble() * 10);
break;
case 1:
c = 'a' + (int) (secureRandom.nextDouble() * 26);
break;
case 2:
c = 'A' + (int) (secureRandom.nextDouble() * 26);
break;
}
}
Do you wish to achieve something like this :
int rand=0,c=0;;
SecureRandom secrnd=new SecureRandom();
for (int i = 0; i < 8; i++) {
rand = (int) (secrnd.nextInt(10)% 3);
switch (rand) {
case 0:
c = '0' + (int) (secrnd.nextInt(10) % 10);
break;
case 1:
c = 'a' + (int) (secrnd.nextInt(10) % 26);
break;
case 2:
c = 'A' + (int) (secrnd.nextInt(10) % 26);
break;
}
System.out.println(c);
}
Please clarify your question , so that i can understand what you want to achieve with the above code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.