# 解密随机数生成器

159人阅读 评论(0)

/**
* An instance of this class is used to generate a stream of
* pseudorandom numbers. The class uses a 48-bit seed, which is
* modified using a linear congruential formula. (See Donald Knuth,
* <i>The Art of Computer Programming, Volume 2</i>, Section 3.2.1.)
* <p>

/**
* Creates a new random number generator. This constructor sets
* the seed of the random number generator to a value very likely
* to be distinct from any other invocation of this constructor.
*/
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}

private static long seedUniquifier() {
// L'Ecuyer, "Tables of Linear Congruential Generators of
// Different Sizes and Good Lattice Structure", 1999
for (;;) {
long current = seedUniquifier.get();
long next = current * 181783497276652981L;
if (seedUniquifier.compareAndSet(current, next))
return next;
}
}

private static final AtomicLong seedUniquifier
= new AtomicLong(8682522807148012L);

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



1、获得一个长整形数作为“初始种子”（系统默认的是8682522807148012L）

2、不断与一个变态的数——181783497276652981L相乘（天知道这些数是不是工程师随便滚键盘滚出来的-.-）直到某一次相乘前后数值相等

3、与系统随机出来的nanotime值作异或运算，得到最终的种子

 protected int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}

线性同余法是一个很古老的随机数生成算法，它的数学形式如下：

Xn+1 = (a*Xn+c)(mod m)

m>0,0<a<m,0<c<m

1. c和m互素;

2. a-1可被所有m的质因数整除;

3. 当m是4的整数倍，a-1也是4的整数倍

 private static long initialScramble(long seed) {
return (seed ^ multiplier) & mask;



    private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;

0.8024508793535536
0.5481799061191626
0.27565830804489333
0.047160003035978115
0.7035259724009703
0.6550010669273417
0.6482388034909883
0.0576209291980867
0.07069050337047089
0.9336952730245858
0.13472579417197172
0.10999371780411427
0.38668647801543354
0.994986602594389
0.37053761228696236
0.4269821582971406
0.30965439072331447
0.26730127990451324
0.15780248921270124
0.4874277631424623
0.43866923824434134
0.8379735008094493
0.46585350668133274
0.03358481257929935
0.8894735657161117
0.46912683775771524
0.9431080765561418
0.9167830882120481
0.17286940293254904
0.19988344534144653
... ...


0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：215次
• 积分：13
• 等级：
• 排名：千里之外
• 原创：0篇
• 转载：1篇
• 译文：1篇
• 评论：0条
文章存档
阅读排行
评论排行