1Random number generation 2======================== 3 4When generating random data for use in cryptographic operations, such as an 5initialization vector for encryption in 6:class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` mode, you do not 7want to use the standard :mod:`random` module APIs. This is because they do not 8provide a cryptographically secure random number generator, which can result in 9major security issues depending on the algorithms in use. 10 11Therefore, it is our recommendation to `always use your operating system's 12provided random number generator`_, which is available as :func:`os.urandom`. 13For example, if you need 16 bytes of random data for an initialization vector, 14you can obtain them with: 15 16.. doctest:: 17 18 >>> import os 19 >>> iv = os.urandom(16) 20 21This will use ``/dev/urandom`` on UNIX platforms, and ``CryptGenRandom`` on 22Windows. 23 24If you need your random number as an integer (for example, for 25:meth:`~cryptography.x509.CertificateBuilder.serial_number`), you can use 26``int.from_bytes`` to convert the result of ``os.urandom``: 27 28.. code-block:: pycon 29 30 >>> serial = int.from_bytes(os.urandom(20), byteorder="big") 31 32Starting with Python 3.6 the `standard library includes`_ the ``secrets`` 33module, which can be used for generating cryptographically secure random 34numbers, with specific helpers for text-based formats. 35 36.. _`always use your operating system's provided random number generator`: https://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/ 37.. _`standard library includes`: https://docs.python.org/3/library/secrets.html 38