Skip to content

Commit 797068c

Browse files
committed
[GR-23763] Fix os.urandom to return uniform first byte
PullRequest: graalpython/992
2 parents c42d934 + 610b0c8 commit 797068c

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/PosixModuleBuiltins.java

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@
5353
import java.io.InputStreamReader;
5454
import java.io.OutputStream;
5555
import java.lang.ProcessBuilder.Redirect;
56-
import java.math.BigInteger;
5756
import java.net.InetAddress;
5857
import java.net.UnknownHostException;
5958
import java.nio.ByteBuffer;
@@ -70,6 +69,8 @@
7069
import java.nio.file.attribute.PosixFilePermission;
7170
import java.nio.file.attribute.PosixFilePermissions;
7271
import java.nio.file.attribute.UserPrincipal;
72+
import java.security.NoSuchAlgorithmException;
73+
import java.security.SecureRandom;
7374
import java.util.Arrays;
7475
import java.util.Collection;
7576
import java.util.HashMap;
@@ -78,7 +79,6 @@
7879
import java.util.Locale;
7980
import java.util.Map;
8081
import java.util.Map.Entry;
81-
import java.util.Random;
8282
import java.util.Set;
8383
import java.util.concurrent.TimeUnit;
8484

@@ -1688,14 +1688,25 @@ public abstract static class ReplaceNode extends RenameNode {
16881688
@GenerateNodeFactory
16891689
@TypeSystemReference(PythonArithmeticTypes.class)
16901690
abstract static class URandomNode extends PythonBuiltinNode {
1691+
private static SecureRandom secureRandom;
1692+
1693+
private static SecureRandom createRandomInstance() {
1694+
try {
1695+
return SecureRandom.getInstance("NativePRNGNonBlocking");
1696+
} catch (NoSuchAlgorithmException e) {
1697+
throw new IllegalStateException(e);
1698+
}
1699+
}
1700+
16911701
@Specialization
16921702
@TruffleBoundary(allowInlining = true)
16931703
PBytes urandom(int size) {
1694-
// size is in bytes
1695-
BigInteger bigInteger = new BigInteger(size * 8, new Random());
1696-
// sign may introduce an extra byte
1697-
byte[] range = Arrays.copyOfRange(bigInteger.toByteArray(), 0, size);
1698-
return factory().createBytes(range);
1704+
if (secureRandom == null) {
1705+
secureRandom = createRandomInstance();
1706+
}
1707+
byte[] bytes = new byte[size];
1708+
secureRandom.nextBytes(bytes);
1709+
return factory().createBytes(bytes);
16991710
}
17001711
}
17011712

0 commit comments

Comments
 (0)