blob: 5d6fd3d897361284a5c439d74b023f7c617eaa57 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
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
provide a cryptographically secure random number generator, which can result in
major security issues depending on the algorithms in use.
Therefore, it is our recommendation to `always use your operating system's
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:
.. doctest::
>>> import os
>>> iv = os.urandom(16)
If you need your random number as an big integer, you can use
``int.from_bytes`` to convert the result of ``os.urandom``:
.. code-block:: pycon
>>> serial = int.from_bytes(os.urandom(16), byteorder="big")
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.
.. _`always use your operating system's provided random number generator`: https://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
.. _`Python standard library`: https://docs.python.org/3/library/secrets.html
|