/
Fortuna.java
162 lines (144 loc) · 6.1 KB
/
Fortuna.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package com.grunka.random.fortuna;
import com.grunka.random.fortuna.accumulator.Accumulator;
import com.grunka.random.fortuna.entropy.BufferPoolEntropySource;
import com.grunka.random.fortuna.entropy.FreeMemoryEntropySource;
import com.grunka.random.fortuna.entropy.GarbageCollectorEntropySource;
import com.grunka.random.fortuna.entropy.LoadAverageEntropySource;
import com.grunka.random.fortuna.entropy.MemoryPoolEntropySource;
import com.grunka.random.fortuna.entropy.SchedulingEntropySource;
import com.grunka.random.fortuna.entropy.ThreadTimeEntropySource;
import com.grunka.random.fortuna.entropy.URandomEntropySource;
import com.grunka.random.fortuna.entropy.UptimeEntropySource;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public class Fortuna extends Random {
private static final int MIN_POOL_SIZE = 64;
private static final int[] POWERS_OF_TWO = initializePowersOfTwo();
private static final int RANDOM_DATA_CHUNK_SIZE = 128 * 1024;
private static int[] initializePowersOfTwo() {
int[] result = new int[32];
for (int power = 0; power < result.length; power++) {
result[power] = (int) StrictMath.pow(2, power);
}
return result;
}
private long lastReseedTime = 0;
private long reseedCount = 0;
private final RandomDataBuffer randomDataBuffer;
private final Generator generator;
private final Accumulator accumulator;
private final ScheduledExecutorService scheduler;
private final boolean createdScheduler;
private final PrefetchingSupplier<byte[]> randomDataPrefetcher;
private static ScheduledExecutorService createDefaultScheduler() {
return Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
private final ThreadFactory delegate = Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable r) {
Thread thread = delegate.newThread(r);
thread.setDaemon(true);
return thread;
}
});
}
public static Fortuna createInstance() {
return new Fortuna();
}
@SuppressWarnings("WeakerAccess")
public static Fortuna createInstance(ScheduledExecutorService scheduler) {
return new Fortuna(scheduler);
}
public Fortuna() {
ScheduledExecutorService scheduler = createDefaultScheduler();
this.createdScheduler = true;
this.generator = new Generator();
this.randomDataBuffer = new RandomDataBuffer();
this.accumulator = createAccumulator(scheduler);
this.randomDataPrefetcher = new PrefetchingSupplier<>(this::randomData, scheduler);
this.scheduler = scheduler;
}
public Fortuna(ScheduledExecutorService scheduler) {
this.createdScheduler = false;
this.generator = new Generator();
this.randomDataBuffer = new RandomDataBuffer();
this.accumulator = createAccumulator(scheduler);
this.randomDataPrefetcher = new PrefetchingSupplier<>(this::randomData, scheduler);
this.scheduler = scheduler;
}
private static Accumulator createAccumulator(ScheduledExecutorService scheduler) {
Pool[] pools = new Pool[32];
for (int pool = 0; pool < pools.length; pool++) {
pools[pool] = new Pool();
}
Accumulator accumulator = new Accumulator(pools, scheduler);
accumulator.addSource(new SchedulingEntropySource());
accumulator.addSource(new GarbageCollectorEntropySource());
accumulator.addSource(new LoadAverageEntropySource());
accumulator.addSource(new FreeMemoryEntropySource());
accumulator.addSource(new ThreadTimeEntropySource());
accumulator.addSource(new UptimeEntropySource());
accumulator.addSource(new BufferPoolEntropySource());
accumulator.addSource(new MemoryPoolEntropySource());
if (Files.exists(Paths.get("/dev/urandom"))) {
accumulator.addSource(new URandomEntropySource());
}
while (pools[0].size() < MIN_POOL_SIZE) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new Error("Interrupted while waiting for initialization", e);
}
}
return accumulator;
}
private byte[] randomData() {
long now = System.currentTimeMillis();
Pool[] pools = accumulator.getPools();
if (pools[0].size() >= MIN_POOL_SIZE && now - lastReseedTime > 100) {
lastReseedTime = now;
reseedCount++;
byte[] seed = new byte[pools.length * 32]; // Maximum potential length
int seedLength = 0;
for (int pool = 0; pool < pools.length; pool++) {
if (reseedCount % POWERS_OF_TWO[pool] == 0) {
System.arraycopy(pools[pool].getAndClear(), 0, seed, seedLength, 32);
seedLength += 32;
}
}
generator.reseed(Arrays.copyOf(seed, seedLength));
}
if (reseedCount == 0) {
throw new IllegalStateException("Generator not reseeded yet");
} else {
return generator.pseudoRandomData(RANDOM_DATA_CHUNK_SIZE);
}
}
@Override
protected int next(int bits) {
return randomDataBuffer.next(bits, randomDataPrefetcher);
}
@Override
public synchronized void setSeed(long seed) {
// Does not do anything
}
@SuppressWarnings("WeakerAccess")
public void shutdown(long timeout, TimeUnit unit) throws InterruptedException {
randomDataPrefetcher.shutdownPrefetch();
accumulator.shutdownSources();
if (createdScheduler) {
scheduler.shutdown();
if (!scheduler.awaitTermination(timeout, unit)) {
scheduler.shutdownNow();
}
}
}
public void shutdown() throws InterruptedException {
shutdown(30, TimeUnit.SECONDS);
}
}