Skip to content

Commit e1d5035

Browse files
author
Zach Olstein
committed
Use SecureRandom for os.urandom
The Random PRNG does not produce random numbers sufficient for cryptographic use, as os.urandom specifies it should. Instead we replace it with an instance of SecureRandom. Because creating SecureRandom instances consumes a significant amount of resources, we store one instance in a static field to share amongst all URandomNodes. We initialize it only on the first call to urandom to avoid incurring the cost on loading the class.
1 parent 79054a2 commit e1d5035

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

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

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@
7070
import java.nio.file.attribute.PosixFilePermission;
7171
import java.nio.file.attribute.PosixFilePermissions;
7272
import java.nio.file.attribute.UserPrincipal;
73+
import java.security.NoSuchAlgorithmException;
74+
import java.security.SecureRandom;
7375
import java.util.Arrays;
7476
import java.util.Collection;
7577
import java.util.HashMap;
@@ -1676,11 +1678,25 @@ public abstract static class ReplaceNode extends RenameNode {
16761678
@GenerateNodeFactory
16771679
@TypeSystemReference(PythonArithmeticTypes.class)
16781680
abstract static class URandomNode extends PythonBuiltinNode {
1681+
private static SecureRandom secureRandom;
1682+
1683+
private static SecureRandom createRandomInstance() {
1684+
try {
1685+
return SecureRandom.getInstance("NativePRNGNonBlocking");
1686+
} catch (NoSuchAlgorithmException e) {
1687+
throw new IllegalStateException(e);
1688+
}
1689+
}
1690+
1691+
16791692
@Specialization
16801693
@TruffleBoundary(allowInlining = true)
16811694
PBytes urandom(int size) {
1695+
if (secureRandom == null) {
1696+
secureRandom = createRandomInstance();
1697+
}
16821698
byte[] bytes = new byte[size];
1683-
new Random().nextBytes(bytes);
1699+
secureRandom.nextBytes(bytes);
16841700
return factory().createBytes(bytes);
16851701
}
16861702
}

0 commit comments

Comments
 (0)