2014-02-06 17:47:07 +00:00
|
|
|
Random number generation
|
|
|
|
|
========================
|
|
|
|
|
|
|
|
|
|
When generating random data for use in cryptographic operations, such as an
|
|
|
|
|
initialization vector for encryption in
|
|
|
|
|
:class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` mode, you do not
|
|
|
|
|
want to use the standard :mod:`random` module APIs. This is because they do not
|
2014-02-06 18:27:48 +00:00
|
|
|
provide a cryptographically secure random number generator, which can result in
|
|
|
|
|
major security issues depending on the algorithms in use.
|
2014-02-06 17:47:07 +00:00
|
|
|
|
2014-02-25 22:12:35 +00:00
|
|
|
Therefore, it is our recommendation to `always use your operating system's
|
2014-12-19 07:48:33 +00:00
|
|
|
provided random number generator`_, which is available as :func:`os.urandom`.
|
|
|
|
|
For example, if you need 16 bytes of random data for an initialization vector,
|
|
|
|
|
you can obtain them with:
|
2014-02-06 17:47:07 +00:00
|
|
|
|
2014-07-12 11:27:37 +00:00
|
|
|
.. doctest::
|
2014-02-06 17:47:07 +00:00
|
|
|
|
|
|
|
|
>>> import os
|
2014-07-12 16:52:59 +00:00
|
|
|
>>> iv = os.urandom(16)
|
2014-02-25 22:12:35 +00:00
|
|
|
|
2014-12-19 05:31:28 +00:00
|
|
|
|
2023-03-09 21:19:39 +00:00
|
|
|
If you need your random number as an big integer, you can use
|
2015-08-08 22:18:09 +00:00
|
|
|
``int.from_bytes`` to convert the result of ``os.urandom``:
|
|
|
|
|
|
|
|
|
|
.. code-block:: pycon
|
|
|
|
|
|
2023-03-09 21:19:39 +00:00
|
|
|
>>> serial = int.from_bytes(os.urandom(16), byteorder="big")
|
2015-08-08 22:18:09 +00:00
|
|
|
|
2022-01-29 15:15:11 +00:00
|
|
|
In addition, the `Python standard library`_ includes the ``secrets`` module,
|
|
|
|
|
which can be used for generating cryptographically secure random numbers, with
|
|
|
|
|
specific helpers for text-based formats.
|
2017-06-04 15:51:31 +00:00
|
|
|
|
2016-11-06 15:13:35 +00:00
|
|
|
.. _`always use your operating system's provided random number generator`: https://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
|
2022-01-29 15:15:11 +00:00
|
|
|
.. _`Python standard library`: https://docs.python.org/3/library/secrets.html
|