Alex Gaynor | 2a70f91 | 2014-02-06 09:47:07 -0800 | [diff] [blame] | 1 | Random number generation |
| 2 | ======================== |
| 3 | |
| 4 | When generating random data for use in cryptographic operations, such as an |
| 5 | initialization vector for encryption in |
| 6 | :class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` mode, you do not |
| 7 | want to use the standard :mod:`random` module APIs. This is because they do not |
Alex Gaynor | cb15716 | 2014-02-06 10:27:48 -0800 | [diff] [blame] | 8 | provide a cryptographically secure random number generator, which can result in |
| 9 | major security issues depending on the algorithms in use. |
Alex Gaynor | 2a70f91 | 2014-02-06 09:47:07 -0800 | [diff] [blame] | 10 | |
Alex Gaynor | 3e4729a | 2014-02-25 14:12:35 -0800 | [diff] [blame] | 11 | Therefore, it is our recommendation to `always use your operating system's |
Alex Gaynor | ae7dfce | 2014-12-18 23:48:33 -0800 | [diff] [blame] | 12 | provided random number generator`_, which is available as :func:`os.urandom`. |
| 13 | For example, if you need 16 bytes of random data for an initialization vector, |
| 14 | you can obtain them with: |
Alex Gaynor | 2a70f91 | 2014-02-06 09:47:07 -0800 | [diff] [blame] | 15 | |
Alex Stapleton | faf305b | 2014-07-12 12:27:37 +0100 | [diff] [blame] | 16 | .. doctest:: |
Alex Gaynor | 2a70f91 | 2014-02-06 09:47:07 -0800 | [diff] [blame] | 17 | |
| 18 | >>> import os |
Alex Gaynor | 6e1fa9b | 2014-07-12 09:52:59 -0700 | [diff] [blame] | 19 | >>> iv = os.urandom(16) |
Alex Gaynor | 3e4729a | 2014-02-25 14:12:35 -0800 | [diff] [blame] | 20 | |
Alex Gaynor | 2d6bb0b | 2014-12-18 21:31:28 -0800 | [diff] [blame] | 21 | This will use ``/dev/urandom`` on UNIX platforms, and ``CryptGenRandom`` on |
| 22 | Windows. |
| 23 | |
Alex Gaynor | 4c360e4 | 2015-08-08 18:18:09 -0400 | [diff] [blame] | 24 | If 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 Gaynor | 140ec5d | 2017-06-04 11:51:31 -0400 | [diff] [blame] | 32 | Starting with Python 3.6 the `standard library includes`_ the ``secrets`` |
| 33 | module, which can be used for generating cryptographically secure random |
| 34 | numbers, with specific helpers for text-based formats. |
| 35 | |
Alex Gaynor | e51236d | 2016-11-06 10:13:35 -0500 | [diff] [blame] | 36 | .. _`always use your operating system's provided random number generator`: https://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/ |
Alex Gaynor | 140ec5d | 2017-06-04 11:51:31 -0400 | [diff] [blame] | 37 | .. _`standard library includes`: https://docs.python.org/3/library/secrets.html |