安全随机散列

SecureRandom hash

我正在尝试查看是否可以根据安全随机散列获得适当的分发。我的第一个索引似乎总是翻倍。我做错了什么吗

    SecureRandom sr = new SecureRandom();

    sr.setSeed(sr.generateSeed(16));
    int zero = 0;
    int one = 0;
    int two = 0;
    int three = 0;
    int four = 0;
    int five = 0;
    int six =0;


    for (int i = 0 ; i < 100000; i++) {
        long index = sr.nextLong()%6;
        if(index == 0)
            zero++;
        else if (index == 1)
            one++;
        else if(index == 2)
            two++;
        else if(index == 3)
            three++;
        else if(index == 4)
            four++;
        else if(index == 5)
            five++;
    }
    System.out.println(zero);
    System.out.println(one);
    System.out.println(two);
    System.out.println(three);
    System.out.println(four);
    System.out.println(five);
    System.out.println(six);

看看输出的第一行

Here is the output
16548
8362
8314
8175
8272
8210

您忽略了 SecureRandom.nextLong() 可以 return 负片这一事实。所以你的代码只捕获了所有非零索引的一半,因为 -7 % 6 == -1,但它捕获了所有零索引,因为 -6 % 6 == 0.

如果您希望所有值都介于 0 和 5 之间,只需使用 Math.abs():

long index = Math.abs(sr.nextLong()%6);

示例输出:

16735
16510
16657
16776
16599
16723