1

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;
    }
}
Impulse The Fox
  • 2,638
  • 2
  • 27
  • 52
the_way
  • 171
  • 4
  • 14
  • 1
    Take a took at [Generate secure random number uniformly over a range in Java](https://stackoverflow.com/questions/28742702/generate-secure-random-number-uniformly-over-a-range-in-java) – Mathjoh Apr 23 '18 at 10:56

3 Answers3

3
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;
    }
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
2

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;
    }
}
Elarbi Mohamed Aymen
  • 1,617
  • 2
  • 14
  • 26
Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29
-1

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.

Vishnu
  • 89
  • 1
  • 7