Java随机化字符串

Jar*_*ida 6 java random nanotime random-seed current-time

我试图在不使用任何Random()函数的情况下生成无意义的单词。我发现我可以使用当前时钟或鼠标坐标。我选择使用当前时钟。这是我写的代码。

private final char[] charray = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
    'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

private char getRandomCharacter(){
    return charray[random(charray.length)];
}

private int random(int value){
    value =(int) System.nanoTime()% 52;
    return value;
}

protected Randomizer(){
    boolean running = true;
    int count = 0;
    int max = 5;
    while(running){
        StringBuilder sb = new StringBuilder();
        int size = random(25) + random(25);
        for (int i = 0; i < size; i++) {
            sb.append(getRandomCharacter());
        }
        System.out.println("Random Line : " + sb.toString());

        if (count++ == max) {
            running = false;
            System.out.println("All of them are random.");
        }
    }
}

public static void main(String[] args) {
    new Randomizer();
}
Run Code Online (Sandbox Code Playgroud)

我期待着这样的输出:

axdlMkjiIfjcmqQopv等。

但我得到这样的东西:

ZNNrrrUUUUxxxxbbbhhhLLLLoooRRRRRvvvYYYYBBBBfffI或JmmmPPKKKKnnnnRRBeeHHHHlllllOOOOrrrVVVVV

为什么会有太多的连续。是nanoTime为还是什么?我用的currentTimeMillis在此之前,它是多沃瑟太慢。我不知道,也找不到任何有关如何使用当前时钟随机化的信息。

Tho*_*ler 2

可以使用计时数据(除了其他数据)来为随机数生成器提供种子,但使用计时数据来实现随机性并不容易。这是可能的,但可能会非常慢。例如,请参阅我在这里编写的有关如何使用其他数据来播种安全随机实例的代码(H2 数据库、MathUtils.generateAlternativeSeed)。它用:

  • System.currentTimeMillis()
  • System.nanoTime()
  • new Object().hashCode()
  • Runtime.freeMemory()、maxMemory()、totalMemory()
  • System.getProperties().toString()
  • Inet地址
  • 更多计时数据

这是为了播种安全的伪随机数生成器。这可以确保即使在没有任何其他运行、不知道当前时间并且没有 UI 的系统上也能获得足够的熵。

但是,正如您所见,依赖计时数据是很困难的,因为它取决于操作系统、方法调用之间的时间、编译器和硬件。