random-numbers.rst 1.5 KB

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