secrets.py 2.0 KB

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