blob: c6acd5b18b1ded4d8796008e9250d66d006af7c3 [file] [log] [blame]
Alex Gaynor2a70f912014-02-06 09:47:07 -08001Random 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
Alex Gaynorcb157162014-02-06 10:27:48 -08008provide a cryptographically secure random number generator, which can result in
9major security issues depending on the algorithms in use.
Alex Gaynor2a70f912014-02-06 09:47:07 -080010
Alex Gaynor3e4729a2014-02-25 14:12:35 -080011Therefore, it is our recommendation to `always use your operating system's
Alex Gaynorae7dfce2014-12-18 23:48:33 -080012provided 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:
Alex Gaynor2a70f912014-02-06 09:47:07 -080015
Alex Stapletonfaf305b2014-07-12 12:27:37 +010016.. doctest::
Alex Gaynor2a70f912014-02-06 09:47:07 -080017
18 >>> import os
Alex Gaynor6e1fa9b2014-07-12 09:52:59 -070019 >>> iv = os.urandom(16)
Alex Gaynor3e4729a2014-02-25 14:12:35 -080020
Alex Gaynor2d6bb0b2014-12-18 21:31:28 -080021This will use ``/dev/urandom`` on UNIX platforms, and ``CryptGenRandom`` on
22Windows.
23
Alex Gaynor4c360e42015-08-08 18:18:09 -040024If 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
Alex Gaynor140ec5d2017-06-04 11:51:31 -040032Starting 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
Alex Gaynore51236d2016-11-06 10:13:35 -050036.. _`always use your operating system's provided random number generator`: https://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
Alex Gaynor140ec5d2017-06-04 11:51:31 -040037.. _`standard library includes`: https://docs.python.org/3/library/secrets.html