Skip to content

Commit 33d2d3b

Browse files
author
Simon Fuet
committed
fix(random): Provide initialized secured random instead of seed
1 parent bc07c06 commit 33d2d3b

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

engine/core/src/main/java/com/codingame/gameengine/core/MultiplayerGameManager.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,11 @@
22

33
import java.io.IOException;
44
import java.io.StringReader;
5+
import java.security.NoSuchAlgorithmException;
6+
import java.security.SecureRandom;
57
import java.util.List;
68
import java.util.Properties;
9+
import java.util.Random;
710
import java.util.Scanner;
811
import java.util.Map.Entry;
912
import java.util.concurrent.ThreadLocalRandom;
@@ -21,8 +24,11 @@
2124
@Singleton
2225
public final class MultiplayerGameManager<T extends AbstractMultiplayerPlayer> extends GameManager<T> {
2326

27+
private static final String RANDOM_SECURE_SHA1PRNG_ALGORITHM = "SHA1PRNG";
28+
2429
private Properties gameParameters;
2530
private long seed;
31+
private Random random;
2632

2733
@Override
2834
protected void readGameProperties(InputCommand iCmd, Scanner s) {
@@ -46,6 +52,15 @@ protected void readGameProperties(InputCommand iCmd, Scanner s) {
4652
}
4753
}
4854
gameParameters.setProperty("seed", String.valueOf(seed));
55+
56+
try {
57+
// This random generator is reproducible whereas default one (native PRNG is not)
58+
random = SecureRandom.getInstance(RANDOM_SECURE_SHA1PRNG_ALGORITHM);
59+
random.setSeed(seed);
60+
} catch (NoSuchAlgorithmException e1) {
61+
log.error("Error while creating secure random number generator. Default to non-secure random generator", e1);
62+
random = new Random(seed);
63+
}
4964
}
5065

5166
@Override
@@ -76,9 +91,14 @@ public int getPlayerCount() {
7691
*
7792
* @return an <code>long</code> containing a given or generated seed.
7893
*/
94+
@Deprecated
7995
public long getSeed() {
8096
return seed;
8197
}
98+
99+
public Random getRandom() {
100+
return random;
101+
}
82102

83103
/**
84104
* <p>

0 commit comments

Comments
 (0)