Skip to content

Commit 79054a2

Browse files
author
Zach Olstein
committed
Fix os.urandom to return uniform first byte
The former implementation of os.urandom generated an N-byte random BigInteger and got its contents as a byte array. However, because the byte array returned by a BigInteger can have one additional byte to account for the sign it truncated the array to only the first N bytes. This causes a big problem with the first byte; any time the high bit of the first byte would have been a 1, it would instead make the entire first byte 0. I've rewritten the urandom function not to use a BigInteger and instead use the Random.nextBytes function. This both fixes the bug and likely makes the code faster because it removes the array-copy needed to truncate the array.
1 parent 6f4b443 commit 79054a2

File tree

1 file changed

+3
-5
lines changed

1 file changed

+3
-5
lines changed

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

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1679,11 +1679,9 @@ abstract static class URandomNode extends PythonBuiltinNode {
16791679
@Specialization
16801680
@TruffleBoundary(allowInlining = true)
16811681
PBytes urandom(int size) {
1682-
// size is in bytes
1683-
BigInteger bigInteger = new BigInteger(size * 8, new Random());
1684-
// sign may introduce an extra byte
1685-
byte[] range = Arrays.copyOfRange(bigInteger.toByteArray(), 0, size);
1686-
return factory().createBytes(range);
1682+
byte[] bytes = new byte[size];
1683+
new Random().nextBytes(bytes);
1684+
return factory().createBytes(bytes);
16871685
}
16881686
}
16891687

0 commit comments

Comments
 (0)