secrets.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """Generate cryptographically strong pseudo-random numbers suitable for
  2. managing secrets such as account authentication, tokens, and similar.
  3. See PEP 506 for more information.
  4. https://peps.python.org/pep-0506/
  5. """
  6. __all__ = ['choice', 'randbelow', 'randbits', 'SystemRandom',
  7. 'token_bytes', 'token_hex', 'token_urlsafe',
  8. 'compare_digest',
  9. ]
  10. import base64
  11. from hmac import compare_digest
  12. from random import SystemRandom
  13. _sysrand = SystemRandom()
  14. randbits = _sysrand.getrandbits
  15. choice = _sysrand.choice
  16. def randbelow(exclusive_upper_bound):
  17. """Return a random int in the range [0, n)."""
  18. if exclusive_upper_bound <= 0:
  19. raise ValueError("Upper bound must be positive.")
  20. return _sysrand._randbelow(exclusive_upper_bound)
  21. DEFAULT_ENTROPY = 32 # number of bytes to return by default
  22. def token_bytes(nbytes=None):
  23. """Return a random byte string containing *nbytes* bytes.
  24. If *nbytes* is ``None`` or not supplied, a reasonable
  25. default is used.
  26. >>> token_bytes(16) #doctest:+SKIP
  27. b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b'
  28. """
  29. if nbytes is None:
  30. nbytes = DEFAULT_ENTROPY
  31. return _sysrand.randbytes(nbytes)
  32. def token_hex(nbytes=None):
  33. """Return a random text string, in hexadecimal.
  34. The string has *nbytes* random bytes, each byte converted to two
  35. hex digits. If *nbytes* is ``None`` or not supplied, a reasonable
  36. default is used.
  37. >>> token_hex(16) #doctest:+SKIP
  38. 'f9bf78b9a18ce6d46a0cd2b0b86df9da'
  39. """
  40. return token_bytes(nbytes).hex()
  41. def token_urlsafe(nbytes=None):
  42. """Return a random URL-safe text string, in Base64 encoding.
  43. The string has *nbytes* random bytes. If *nbytes* is ``None``
  44. or not supplied, a reasonable default is used.
  45. >>> token_urlsafe(16) #doctest:+SKIP
  46. 'Drmhze6EPcv0fN_81Bj-nA'
  47. """
  48. tok = token_bytes(nbytes)
  49. return base64.urlsafe_b64encode(tok).rstrip(b'=').decode('ascii')