如何使用SecureRandom生成随机数

时间:2018-04-23 10:49:59

标签: java

我有以下使用java.util.Random的代码,现在我想更改为java.security.SecureRandom。如何使用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;
    }
}

3 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分:1)

secureRandomObject.nextDouble()基本上等同于Math.random()

以下代码将起作用......

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;
    }
}

答案 2 :(得分:-1)

你希望实现这样的目标:

    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);
}

请澄清您的问题,以便我能够理解您希望使用上述代码实现的目标。

相关问题