secrets.py 2.0 KB

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