rand — An interface to the OpenSSL pseudo random number generator

Warning

Functions from this module shouldn’t be used. Use urandom instead.

This module handles the OpenSSL pseudo random number generator (PRNG) and declares the following:

OpenSSL.rand.add(buffer, entropy)

Mix bytes from string into the PRNG state.

The entropy argument is (the lower bound of) an estimate of how much randomness is contained in string, measured in bytes.

For more information, see e.g. RFC 1750.

Parameters:
  • buffer – Buffer with random data.
  • entropy – The entropy (in bytes) measurement of the buffer.
Returns:

None

OpenSSL.rand.bytes(num_bytes)

Get some random bytes from the PRNG as a string.

This is a wrapper for the C function RAND_bytes.

Parameters:num_bytes – The number of bytes to fetch.
Returns:A string of random bytes.
OpenSSL.rand.cleanup()

Erase the memory used by the PRNG.

This is a wrapper for the C function RAND_cleanup.

Returns:None
OpenSSL.rand.egd(path[, bytes])

Query the system random source and seed the PRNG.

Does not actually query the EGD.

Deprecated since version 16.0.0: EGD was only necessary for some commercial UNIX systems that all reached their ends of life more than a decade ago. See pyca/cryptography#1636.

Parameters:
  • path – Ignored.
  • bytes – (optional) The number of bytes to read, default is 255.
Returns:

len(bytes) or 255 if not specified.

OpenSSL.rand.load_file(filename[, bytes])

Read maxbytes of data from filename and seed the PRNG with it.

Read the whole file if maxbytes is not specified or negative.

Parameters:
  • filename – The file to read data from (bytes or unicode).
  • maxbytes – (optional) The number of bytes to read. Default is to read the entire file.
Returns:

The number of bytes read

OpenSSL.rand.seed(buffer)

Equivalent to calling add() with entropy as the length of buffer.

Parameters:buffer – Buffer with random data
Returns:None
OpenSSL.rand.status()

Check whether the PRNG has been seeded with enough data.

Returns:1 if the PRNG is seeded enough, 0 otherwise.
OpenSSL.rand.write_file(filename)

Write a number of random bytes (currently 1024) to the file path. This file can then be used with load_file() to seed the PRNG again.

Parameters:filename – The file to write data to (bytes or unicode).
Returns:The number of bytes written.
OpenSSL.rand.screen()

Add the current contents of the screen to the PRNG state.

Availability: Windows.

Returns:None
exception OpenSSL.rand.Error

An error occurred in an OpenSSL.rand API.

If the current RAND method supports any errors, this is raised when needed. The default method does not raise this when the entropy pool is depleted.

Whenever this exception is raised directly, it has a list of error messages from the OpenSSL error queue, where each item is a tuple (lib, function, reason). Here lib, function and reason are all strings, describing where and what the problem is.

See err(3) for more information.