[Python-Dev] [Python-checkins] cpython: Issue #12049: Add RAND_bytes() and RAND_pseudo_bytes() functions to the ssl

Victor Stinner victor.stinner at haypocalc.com
Wed May 25 11:39:52 CEST 2011


Le mercredi 25 mai 2011 à 08:59 +0300, Petri Lehtinen a écrit :
> So it seems to me that RAND_bytes() either returns cryptographically
> strong data or fails (is it possible to detect the failure with the
> Python function? Should this be documented?).

RAND_bytes() raises an SSLError on error. You can check if there is
enough entropy before calling RAND_bytes() using RAND_status(). I
documented this two infos.

> RAND_pseudo_bytes() always succeeds...

No, it can fail if the RAND method was changed and the current RAND
method doesn't support this operation.

Example:
----
>>> import ctypes
>>> from ctypes import c_void_p
>>> libssl=ctypes.cdll.LoadLibrary('libssl.so')
>>> RAND_set_rand_method=libssl.RAND_set_rand_method
>>> class rand_meth_st(ctypes.Structure): _fields_ = (('seed',
c_void_p), ('bytes', c_void_p), ('cleanup', c_void_p), ('add',
c_void_p), ('pseudorand', c_void_p), ('status', c_void_p))
... 
>>> not_supported = rand_meth_st()
>>> RAND_set_rand_method(ctypes.byref(not_supported))
>>> import ssl
>>> ssl.RAND_bytes(1)
...
ssl.SSLError: [Errno 0] None
>>> ssl.RAND_pseudo_bytes(1)
...
ssl.SSLError: [Errno 0] None
------

Cool, ssl.RAND_pseudo_bytes() raises also an error, as expected :-)

> ... but does not necessarily generate cryptographically
> strong data.

Yes, if the PRNG was not seed with enough data, the RAND_pseudo_bytes()
Python function returns (random_bytes, False).

> > >We may also add a link from random to SSL.RAND_bytes() and
> > >SSL.RAND_pseudo_bytes().
> 
> Obviously, the user needs to be familiar with the concept of
> "cryptographically strong randomness" to use these functions.

I already patched the doc of the random module to add a security
warning. Well, you don't really need to know how a CSPRNG is
implemented, just that random cannot be used for security and that
ssl.RAND_bytes() raises an error if was seeded with enough data.

Tell me if my warning is not clear:

.. warning::

   The generators of the :mod:`random` module should not be used for
   security purposes, they are not cryptographic. Use ssl.RAND_bytes()
   if you require a cryptographically secure pseudorandom number
   generator.

Victor



More information about the Python-Dev mailing list