Java 隨機數 Random VS SecureRandom

更多 Java 基礎知識方面的文章,請參見文集《Java 基礎知識》


1. Math.random() 靜態方法

產生的隨機數是 0 - 1 之間的一個 double,即 0 <= random <= 1
使用:

for (int i = 0; i < 10; i++) {
  System.out.println(Math.random());
}

結果:

0.3598613895606426
0.2666778145365811
0.25090731064243355
0.011064998061666276
0.600686228175639
0.9084006027629496
0.12700524654847833
0.6084605849069343
0.7290804782514261
0.9923831908303121

實現原理:

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random()
This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

當第一次調用 Math.random() 方法時,自動創建了一個偽隨機數生成器,實際上用的是 new java.util.Random()
當接下來繼續調用 Math.random() 方法時,就會使用這個新的偽隨機數生成器

源碼如下:

public static double random() {
    Random rnd = randomNumberGenerator;
    if (rnd == null) rnd = initRNG(); // 第一次調用,創建一個偽隨機數生成器
    return rnd.nextDouble();
}

private static synchronized Random initRNG() {
    Random rnd = randomNumberGenerator;
    return (rnd == null) ? (randomNumberGenerator = new Random()) : rnd; // 實際上用的是new java.util.Random()
}

This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

initRNG() 方法是 synchronized 的,因此在多線程情況下,只有一個線程會負責創建偽隨機數生成器(使用當前時間作為種子),其他線程則利用該偽隨機數生成器產生隨機數。

因此 Math.random() 方法是線程安全的。

什么情況下隨機數的生成線程不安全:

  • 線程1在第一次調用 random() 時產生一個生成器 generator1,使用當前時間作為種子。
  • 線程2在第一次調用 random() 時產生一個生成器 generator2,使用當前時間作為種子。
  • 碰巧 generator1generator2 使用相同的種子,導致 generator1 以后產生的隨機數每次都和 generator2 以后產生的隨機數相同。

什么情況下隨機數的生成線程安全: Math.random() 靜態方法使用

  • 線程1在第一次調用 random() 時產生一個生成器 generator1,使用當前時間作為種子。
  • 線程2在第一次調用 random() 時發現已經有一個生成器 generator1,則直接使用生成器 generator1
public class JavaRandom {
    public static void main(String args[]) {
        new MyThread().start();
        new MyThread().start();
    }
}
class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 2; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + Math.random());
        }
    }
}

結果:

Thread-1: 0.8043581595645333
Thread-0: 0.9338269554390357
Thread-1: 0.5571569413128877
Thread-0: 0.37484586843392464

2. java.util.Random 工具類

基本算法:linear congruential pseudorandom number generator (LGC) 線性同余法偽隨機數生成器
缺點:可預測

An attacker will simply compute the seed from the output values observed. This takes significantly less time than 2^48 in the case of java.util.Random.
從輸出中可以很容易計算出種子值。
It is shown that you can predict future Random outputs observing only two(!) output values in time roughly 2^16.
因此可以預測出下一個輸出的隨機數。
You should never use an LCG for security-critical purposes.
在注重信息安全的應用中,不要使用 LCG 算法生成隨機數,請使用 SecureRandom。

使用:

Random random = new Random();

for (int i = 0; i < 5; i++) {
    System.out.println(random.nextInt());
}

結果:

-24520987
-96094681
-952622427
300260419
1489256498

Random類默認使用當前系統時鐘作為種子:

public Random() {
    this(seedUniquifier() ^ System.nanoTime());
}

public Random(long seed) {
    if (getClass() == Random.class)
        this.seed = new AtomicLong(initialScramble(seed));
    else {
        // subclass might have overriden setSeed
        this.seed = new AtomicLong();
        setSeed(seed);
    }
}

Random類提供的方法:API

  • nextBoolean() - 返回均勻分布的 true 或者 false
  • nextBytes(byte[] bytes)
  • nextDouble() - 返回 0.0 到 1.0 之間的均勻分布的 double
  • nextFloat() - 返回 0.0 到 1.0 之間的均勻分布的 float
  • nextGaussian()- 返回 0.0 到 1.0 之間的高斯分布(即正態分布)的 double
  • nextInt() - 返回均勻分布的 int
  • nextInt(int n) - 返回 0 到 n 之間的均勻分布的 int (包括 0,不包括 n)
  • nextLong() - 返回均勻分布的 long
  • setSeed(long seed) - 設置種子

只要種子一樣,產生的隨機數也一樣: 因為種子確定,隨機數算法也確定,因此輸出是確定的!

Random random1 = new Random(10000);
Random random2 = new Random(10000);

for (int i = 0; i < 5; i++) {
    System.out.println(random1.nextInt() + " = " + random2.nextInt());
}

結果:

-498702880 = -498702880
-858606152 = -858606152
1942818232 = 1942818232
-1044940345 = -1044940345
1588429001 = 1588429001

3. java.util.concurrent.ThreadLocalRandom 工具類

ThreadLocalRandom 是 JDK 7 之后提供,也是繼承至 java.util.Random。

private static final ThreadLocal<ThreadLocalRandom> localRandom =
    new ThreadLocal<ThreadLocalRandom>() {
        protected ThreadLocalRandom initialValue() {
            return new ThreadLocalRandom();
        }
};

每一個線程有一個獨立的隨機數生成器,用于并發產生隨機數,能夠解決多個線程發生的競爭爭奪。效率更高!
ThreadLocalRandom 不是直接用 new 實例化,而是第一次使用其靜態方法 current() 得到 ThreadLocal<ThreadLocalRandom> 實例,然后調用 java.util.Random 類提供的方法獲得各種隨機數。
使用:

public class JavaRandom {
    public static void main(String args[]) {
        new MyThread().start();
        new MyThread().start();
    }
}
class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 2; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + ThreadLocalRandom.current().nextDouble());
        }
    }
}

結果:

Thread-0: 0.13267085355389086
Thread-1: 0.1138484950410098
Thread-0: 0.17187774671469858
Thread-1: 0.9305225910262372

4. java.Security.SecureRandom

也是繼承至 java.util.Random。

Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.
SecureRandom takes Random Data from your os (they can be interval between keystrokes etc - most os collect these data store them in files - /dev/random and /dev/urandom in case of linux/solaris) and uses that as the seed.
操作系統收集了一些隨機事件,比如鼠標點擊,鍵盤點擊等等,SecureRandom 使用這些隨機事件作為種子。

SecureRandom 提供加密的強隨機數生成器 (RNG),要求種子必須是不可預知的,產生非確定性輸出。
SecureRandom 也提供了與實現無關的算法,因此,調用方(應用程序代碼)會請求特定的 RNG 算法并將它傳回到該算法的 SecureRandom 對象中。

  • 如果僅指定算法名稱,如下所示:
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");

  • 如果既指定了算法名稱又指定了包提供程序,如下所示:
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

使用:

SecureRandom random1 = SecureRandom.getInstance("SHA1PRNG");
SecureRandom random2 = SecureRandom.getInstance("SHA1PRNG");

for (int i = 0; i < 5; i++) {
    System.out.println(random1.nextInt() + " != " + random2.nextInt());
}

結果:

704046703 != 2117229935
60819811 != 107252259
425075610 != -295395347
682299589 != -1637998900
-1147654329 != 1418666937

5. 隨機字符串

可以使用 Apache Commons-Lang 包中的 RandomStringUtils 類。
Maven 依賴如下:

<dependency>
    <groupId>commons-lang</groupId>
    <artifactId>commons-lang</artifactId>
    <version>2.6</version>
</dependency>

API 參考:https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html

示例:

public class RandomStringDemo {
    public static void main(String[] args) {
        // Creates a 64 chars length random string of number.
        String result = RandomStringUtils.random(64, false, true);
        System.out.println("random = " + result);

        // Creates a 64 chars length of random alphabetic string.
        result = RandomStringUtils.randomAlphabetic(64);
        System.out.println("random = " + result);

        // Creates a 32 chars length of random ascii string.
        result = RandomStringUtils.randomAscii(32);
        System.out.println("random = " + result);

        // Creates a 32 chars length of string from the defined array of
        // characters including numeric and alphabetic characters.
        result = RandomStringUtils.random(32, 0, 20, true, true, "qw32rfHIJk9iQ8Ud7h0X".toCharArray());
        System.out.println("random = " + result);

    }
}

RandomStringUtils 類的實現上也是依賴了 java.util.Random 工具類:

RandomStringUtils 類的定義


引用:
http://yangzb.iteye.com/blog/325264
Difference between java.util.Random and java.security.SecureRandom

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,963評論 6 542
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,348評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,083評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,706評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,442評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,802評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,795評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,983評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,542評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,287評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,486評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,030評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,710評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,116評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,412評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,224評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,462評論 2 378

推薦閱讀更多精彩內容