Reputation: 117
os.urandom or ssl.RAND_bytes: when generating random bytes for cryptographic purposes, which is more recommended?
If neither one is better, what are the tradeoffs and what is to be expected from each in terms of differences?
Note that ssl.RAND_bytes only exists in Python 3.
Upvotes: 3
Views: 1394
Reputation: 94028
ssl.RAND_bytes
needs to be seeded before it can be used. So you cannot just rely on ssl.RAND_bytes
alone. Both os.urandom
and `ssl.RAND_bytes
are pseudo random number generators. PRNG's are deterministic; when seeded with the same data, they will return the same stream of pseudo random number bytes. These bytes should be indistinguishable from true random if an observer does not know the seed value. os.urandom
however is normally (re-)seeded using a source of entropy within the operating system.
Using os.urandom
should therefore be preferred over ssl.RAND_bytes
. First of all, it is already seeded (and will be reseeded by the operating system). Furthermore, it does not require an additional dependency on an SSL library. A drawback could be performance. It is probably faster to use ssl.RAND_bytes
seeded with a big enough value from os.urandom
as os.urandom
requires a system call any time you retrieve data.
Upvotes: 2