PATH:
usr
/
share
/
doc
/
python3-docs
/
html
/
_sources
/
library
:mod:`secrets` --- Generate secure random numbers for managing secrets ====================================================================== .. module:: secrets :synopsis: Generate secure random numbers for managing secrets. .. moduleauthor:: Steven D'Aprano <steve+python@pearwood.info> .. sectionauthor:: Steven D'Aprano <steve+python@pearwood.info> .. versionadded:: 3.6 .. testsetup:: from secrets import * __name__ = '<doctest>' **Source code:** :source:`Lib/secrets.py` ------------- The :mod:`secrets` module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets. In particularly, :mod:`secrets` should be used in preference to the default pseudo-random number generator in the :mod:`random` module, which is designed for modelling and simulation, not security or cryptography. .. seealso:: :pep:`506` Random numbers -------------- The :mod:`secrets` module provides access to the most secure source of randomness that your operating system provides. .. class:: SystemRandom A class for generating random numbers using the highest-quality sources provided by the operating system. See :class:`random.SystemRandom` for additional details. .. function:: choice(sequence) Return a randomly-chosen element from a non-empty sequence. .. function:: randbelow(n) Return a random int in the range [0, *n*). .. function:: randbits(k) Return an int with *k* random bits. Generating tokens ----------------- The :mod:`secrets` module provides functions for generating secure tokens, suitable for applications such as password resets, hard-to-guess URLs, and similar. .. function:: token_bytes([nbytes=None]) Return a random byte string containing *nbytes* number of bytes. If *nbytes* is ``None`` or not supplied, a reasonable default is used. .. doctest:: >>> token_bytes(16) #doctest:+SKIP b'\xebr\x17D*t\xae\xd4\xe3S\xb6\xe2\xebP1\x8b' .. function:: token_hex([nbytes=None]) Return a random text string, in hexadecimal. The string has *nbytes* random bytes, each byte converted to two hex digits. If *nbytes* is ``None`` or not supplied, a reasonable default is used. .. doctest:: >>> token_hex(16) #doctest:+SKIP 'f9bf78b9a18ce6d46a0cd2b0b86df9da' .. function:: token_urlsafe([nbytes=None]) Return a random URL-safe text string, containing *nbytes* random bytes. The text is Base64 encoded, so on average each byte results in approximately 1.3 characters. If *nbytes* is ``None`` or not supplied, a reasonable default is used. .. doctest:: >>> token_urlsafe(16) #doctest:+SKIP 'Drmhze6EPcv0fN_81Bj-nA' How many bytes should tokens use? ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ To be secure against `brute-force attacks <https://en.wikipedia.org/wiki/Brute-force_attack>`_, tokens need to have sufficient randomness. Unfortunately, what is considered sufficient will necessarily increase as computers get more powerful and able to make more guesses in a shorter period. As of 2015, it is believed that 32 bytes (256 bits) of randomness is sufficient for the typical use-case expected for the :mod:`secrets` module. For those who want to manage their own token length, you can explicitly specify how much randomness is used for tokens by giving an :class:`int` argument to the various ``token_*`` functions. That argument is taken as the number of bytes of randomness to use. Otherwise, if no argument is provided, or if the argument is ``None``, the ``token_*`` functions will use a reasonable default instead. .. note:: That default is subject to change at any time, including during maintenance releases. Other functions --------------- .. function:: compare_digest(a, b) Return ``True`` if strings *a* and *b* are equal, otherwise ``False``, in such a way as to reduce the risk of `timing attacks <http://codahale.com/a-lesson-in-timing-attacks/>`_. See :func:`hmac.compare_digest` for additional details. Recipes and best practices -------------------------- This section shows recipes and best practices for using :mod:`secrets` to manage a basic level of security. Generate an eight-character alphanumeric password: .. testcode:: import string alphabet = string.ascii_letters + string.digits password = ''.join(choice(alphabet) for i in range(8)) .. note:: Applications should not `store passwords in a recoverable format <http://cwe.mitre.org/data/definitions/257.html>`_, whether plain text or encrypted. They should be salted and hashed using a cryptographically-strong one-way (irreversible) hash function. Generate a ten-character alphanumeric password with at least one lowercase character, at least one uppercase character, and at least three digits: .. testcode:: import string alphabet = string.ascii_letters + string.digits while True: password = ''.join(choice(alphabet) for i in range(10)) if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3): break Generate an `XKCD-style passphrase <http://xkcd.com/936/>`_: .. testcode:: # On standard Linux systems, use a convenient dictionary file. # Other platforms may need to provide their own word-list. with open('/usr/share/dict/words') as f: words = [word.strip() for word in f] password = ' '.join(choice(words) for i in range(4)) Generate a hard-to-guess temporary URL containing a security token suitable for password recovery applications: .. testcode:: url = 'https://mydomain.com/reset=' + token_urlsafe() .. # This modeline must appear within the last ten lines of the file. kate: indent-width 3; remove-trailing-space on; replace-tabs on; encoding utf-8;
[+]
..
[-] crypt.rst.txt
[edit]
[-] logging.handlers.rst.txt
[edit]
[-] __main__.rst.txt
[edit]
[-] pty.rst.txt
[edit]
[-] email.rst.txt
[edit]
[-] traceback.rst.txt
[edit]
[-] fileinput.rst.txt
[edit]
[-] xml.sax.reader.rst.txt
[edit]
[-] curses.rst.txt
[edit]
[-] copy.rst.txt
[edit]
[-] aifc.rst.txt
[edit]
[-] xmlrpc.client.rst.txt
[edit]
[-] pydoc.rst.txt
[edit]
[-] asyncio-eventloops.rst.txt
[edit]
[-] uuid.rst.txt
[edit]
[-] functional.rst.txt
[edit]
[-] posix.rst.txt
[edit]
[-] hashlib.rst.txt
[edit]
[-] cmd.rst.txt
[edit]
[-] nntplib.rst.txt
[edit]
[-] python.rst.txt
[edit]
[-] types.rst.txt
[edit]
[-] exceptions.rst.txt
[edit]
[-] tracemalloc.rst.txt
[edit]
[-] othergui.rst.txt
[edit]
[-] xml.dom.pulldom.rst.txt
[edit]
[-] inspect.rst.txt
[edit]
[-] asyncio-stream.rst.txt
[edit]
[-] i18n.rst.txt
[edit]
[-] concurrent.rst.txt
[edit]
[-] imghdr.rst.txt
[edit]
[-] spwd.rst.txt
[edit]
[-] os.path.rst.txt
[edit]
[-] email.message.rst.txt
[edit]
[-] random.rst.txt
[edit]
[-] fileformats.rst.txt
[edit]
[-] faulthandler.rst.txt
[edit]
[-] parser.rst.txt
[edit]
[-] stat.rst.txt
[edit]
[-] code.rst.txt
[edit]
[-] email.headerregistry.rst.txt
[edit]
[-] timeit.rst.txt
[edit]
[-] optparse.rst.txt
[edit]
[-] smtplib.rst.txt
[edit]
[-] filesys.rst.txt
[edit]
[-] email.mime.rst.txt
[edit]
[-] itertools.rst.txt
[edit]
[-] sys.rst.txt
[edit]
[-] bdb.rst.txt
[edit]
[-] stringprep.rst.txt
[edit]
[-] asyncio-subprocess.rst.txt
[edit]
[-] decimal.rst.txt
[edit]
[-] unicodedata.rst.txt
[edit]
[-] intro.rst.txt
[edit]
[-] constants.rst.txt
[edit]
[-] xmlrpc.rst.txt
[edit]
[-] grp.rst.txt
[edit]
[-] pickle.rst.txt
[edit]
[-] mmap.rst.txt
[edit]
[-] debug.rst.txt
[edit]
[-] unittest.mock-examples.rst.txt
[edit]
[-] undoc.rst.txt
[edit]
[-] functools.rst.txt
[edit]
[-] ssl.rst.txt
[edit]
[-] locale.rst.txt
[edit]
[-] secrets.rst.txt
[edit]
[-] pprint.rst.txt
[edit]
[-] email.header.rst.txt
[edit]
[-] email.contentmanager.rst.txt
[edit]
[-] _thread.rst.txt
[edit]
[-] errno.rst.txt
[edit]
[-] sunau.rst.txt
[edit]
[-] syslog.rst.txt
[edit]
[-] tkinter.ttk.rst.txt
[edit]
[-] distribution.rst.txt
[edit]
[-] pdb.rst.txt
[edit]
[-] distutils.rst.txt
[edit]
[-] dummy_threading.rst.txt
[edit]
[-] text.rst.txt
[edit]
[-] socketserver.rst.txt
[edit]
[-] _dummy_thread.rst.txt
[edit]
[-] persistence.rst.txt
[edit]
[-] asyncio-eventloop.rst.txt
[edit]
[-] collections.abc.rst.txt
[edit]
[-] fnmatch.rst.txt
[edit]
[-] quopri.rst.txt
[edit]
[-] http.server.rst.txt
[edit]
[-] keyword.rst.txt
[edit]
[-] xml.dom.rst.txt
[edit]
[-] cgi.rst.txt
[edit]
[-] heapq.rst.txt
[edit]
[-] email.iterators.rst.txt
[edit]
[-] io.rst.txt
[edit]
[-] curses.panel.rst.txt
[edit]
[-] winreg.rst.txt
[edit]
[-] urllib.parse.rst.txt
[edit]
[-] unix.rst.txt
[edit]
[-] getpass.rst.txt
[edit]
[-] sched.rst.txt
[edit]
[-] socket.rst.txt
[edit]
[-] pipes.rst.txt
[edit]
[-] email.compat32-message.rst.txt
[edit]
[-] asyncio-sync.rst.txt
[edit]
[-] modulefinder.rst.txt
[edit]
[-] html.entities.rst.txt
[edit]
[-] ctypes.rst.txt
[edit]
[-] pyexpat.rst.txt
[edit]
[-] pyclbr.rst.txt
[edit]
[-] html.rst.txt
[edit]
[-] test.rst.txt
[edit]
[-] markup.rst.txt
[edit]
[-] doctest.rst.txt
[edit]
[-] csv.rst.txt
[edit]
[-] colorsys.rst.txt
[edit]
[-] xml.sax.rst.txt
[edit]
[-] zlib.rst.txt
[edit]
[-] subprocess.rst.txt
[edit]
[-] base64.rst.txt
[edit]
[-] platform.rst.txt
[edit]
[-] binascii.rst.txt
[edit]
[-] http.rst.txt
[edit]
[-] nis.rst.txt
[edit]
[-] statistics.rst.txt
[edit]
[-] sqlite3.rst.txt
[edit]
[-] json.rst.txt
[edit]
[-] gzip.rst.txt
[edit]
[-] netdata.rst.txt
[edit]
[-] pkgutil.rst.txt
[edit]
[-] linecache.rst.txt
[edit]
[-] cgitb.rst.txt
[edit]
[-] archiving.rst.txt
[edit]
[-] argparse.rst.txt
[edit]
[-] wsgiref.rst.txt
[edit]
[-] tokenize.rst.txt
[edit]
[-] mm.rst.txt
[edit]
[-] telnetlib.rst.txt
[edit]
[-] ossaudiodev.rst.txt
[edit]
[-] tk.rst.txt
[edit]
[-] string.rst.txt
[edit]
[-] misc.rst.txt
[edit]
[-] marshal.rst.txt
[edit]
[-] email.encoders.rst.txt
[edit]
[-] array.rst.txt
[edit]
[-] queue.rst.txt
[edit]
[-] copyreg.rst.txt
[edit]
[-] atexit.rst.txt
[edit]
[-] signal.rst.txt
[edit]
[-] collections.rst.txt
[edit]
[-] tkinter.scrolledtext.rst.txt
[edit]
[-] tempfile.rst.txt
[edit]
[-] codeop.rst.txt
[edit]
[-] threading.rst.txt
[edit]
[-] enum.rst.txt
[edit]
[-] imp.rst.txt
[edit]
[-] crypto.rst.txt
[edit]
[-] bisect.rst.txt
[edit]
[-] dbm.rst.txt
[edit]
[-] formatter.rst.txt
[edit]
[-] language.rst.txt
[edit]
[-] trace.rst.txt
[edit]
[-] tkinter.tix.rst.txt
[edit]
[-] smtpd.rst.txt
[edit]
[-] asyncio-task.rst.txt
[edit]
[-] abc.rst.txt
[edit]
[-] gettext.rst.txt
[edit]
[-] concurrency.rst.txt
[edit]
[-] allos.rst.txt
[edit]
[-] xml.sax.utils.rst.txt
[edit]
[-] tty.rst.txt
[edit]
[-] mailcap.rst.txt
[edit]
[-] msvcrt.rst.txt
[edit]
[-] reprlib.rst.txt
[edit]
[-] development.rst.txt
[edit]
[-] contextlib.rst.txt
[edit]
[-] configparser.rst.txt
[edit]
[-] symbol.rst.txt
[edit]
[-] shlex.rst.txt
[edit]
[-] tabnanny.rst.txt
[edit]
[-] asyncio-dev.rst.txt
[edit]
[-] py_compile.rst.txt
[edit]
[-] uu.rst.txt
[edit]
[-] logging.rst.txt
[edit]
[-] runpy.rst.txt
[edit]
[-] pathlib.rst.txt
[edit]
[-] os.rst.txt
[edit]
[-] urllib.request.rst.txt
[edit]
[-] html.parser.rst.txt
[edit]
[-] bz2.rst.txt
[edit]
[-] binhex.rst.txt
[edit]
[-] time.rst.txt
[edit]
[-] zipapp.rst.txt
[edit]
[-] fcntl.rst.txt
[edit]
[-] tkinter.rst.txt
[edit]
[-] glob.rst.txt
[edit]
[-] email.policy.rst.txt
[edit]
[-] pwd.rst.txt
[edit]
[-] numeric.rst.txt
[edit]
[-] winsound.rst.txt
[edit]
[-] urllib.robotparser.rst.txt
[edit]
[-] selectors.rst.txt
[edit]
[-] xdrlib.rst.txt
[edit]
[-] webbrowser.rst.txt
[edit]
[-] zipfile.rst.txt
[edit]
[-] ipc.rst.txt
[edit]
[-] mailbox.rst.txt
[edit]
[-] plistlib.rst.txt
[edit]
[-] getopt.rst.txt
[edit]
[-] concurrent.futures.rst.txt
[edit]
[-] symtable.rst.txt
[edit]
[-] rlcompleter.rst.txt
[edit]
[-] __future__.rst.txt
[edit]
[-] asynchat.rst.txt
[edit]
[-] audioop.rst.txt
[edit]
[-] compileall.rst.txt
[edit]
[-] unittest.mock.rst.txt
[edit]
[-] dis.rst.txt
[edit]
[-] index.rst.txt
[edit]
[-] logging.config.rst.txt
[edit]
[-] gc.rst.txt
[edit]
[-] shutil.rst.txt
[edit]
[-] sndhdr.rst.txt
[edit]
[-] ipaddress.rst.txt
[edit]
[-] asyncio-queue.rst.txt
[edit]
[-] curses.ascii.rst.txt
[edit]
[-] builtins.rst.txt
[edit]
[-] calendar.rst.txt
[edit]
[-] sysconfig.rst.txt
[edit]
[-] token.rst.txt
[edit]
[-] xml.dom.minidom.rst.txt
[edit]
[-] textwrap.rst.txt
[edit]
[-] importlib.rst.txt
[edit]
[-] fpectl.rst.txt
[edit]
[-] mimetypes.rst.txt
[edit]
[-] netrc.rst.txt
[edit]
[-] fractions.rst.txt
[edit]
[-] select.rst.txt
[edit]
[-] lzma.rst.txt
[edit]
[-] math.rst.txt
[edit]
[-] frameworks.rst.txt
[edit]
[-] ftplib.rst.txt
[edit]
[-] macpath.rst.txt
[edit]
[-] numbers.rst.txt
[edit]
[-] xml.etree.elementtree.rst.txt
[edit]
[-] pickletools.rst.txt
[edit]
[-] asyncore.rst.txt
[edit]
[-] warnings.rst.txt
[edit]
[-] resource.rst.txt
[edit]
[-] unittest.rst.txt
[edit]
[-] datetime.rst.txt
[edit]
[-] asyncio-protocol.rst.txt
[edit]
[-] urllib.rst.txt
[edit]
[-] superseded.rst.txt
[edit]
[-] email.generator.rst.txt
[edit]
[-] ensurepip.rst.txt
[edit]
[-] ast.rst.txt
[edit]
[-] modules.rst.txt
[edit]
[-] venv.rst.txt
[edit]
[-] internet.rst.txt
[edit]
[-] chunk.rst.txt
[edit]
[-] asyncio.rst.txt
[edit]
[-] turtle.rst.txt
[edit]
[-] struct.rst.txt
[edit]
[-] profile.rst.txt
[edit]
[-] urllib.error.rst.txt
[edit]
[-] http.cookiejar.rst.txt
[edit]
[-] tarfile.rst.txt
[edit]
[-] http.cookies.rst.txt
[edit]
[-] multiprocessing.rst.txt
[edit]
[-] msilib.rst.txt
[edit]
[-] xmlrpc.server.rst.txt
[edit]
[-] termios.rst.txt
[edit]
[-] 2to3.rst.txt
[edit]
[-] windows.rst.txt
[edit]
[-] email.examples.rst.txt
[edit]
[-] readline.rst.txt
[edit]
[-] binary.rst.txt
[edit]
[-] shelve.rst.txt
[edit]
[-] re.rst.txt
[edit]
[-] xml.sax.handler.rst.txt
[edit]
[-] hmac.rst.txt
[edit]
[-] datatypes.rst.txt
[edit]
[-] typing.rst.txt
[edit]
[-] custominterp.rst.txt
[edit]
[-] email.charset.rst.txt
[edit]
[-] email.util.rst.txt
[edit]
[-] zipimport.rst.txt
[edit]
[-] cmath.rst.txt
[edit]
[-] idle.rst.txt
[edit]
[-] operator.rst.txt
[edit]
[-] site.rst.txt
[edit]
[-] email.parser.rst.txt
[edit]
[-] functions.rst.txt
[edit]
[-] poplib.rst.txt
[edit]
[-] filecmp.rst.txt
[edit]
[-] codecs.rst.txt
[edit]
[-] imaplib.rst.txt
[edit]
[-] stdtypes.rst.txt
[edit]
[-] difflib.rst.txt
[edit]
[-] weakref.rst.txt
[edit]
[-] http.client.rst.txt
[edit]
[-] email.errors.rst.txt
[edit]
[-] xml.rst.txt
[edit]
[-] wave.rst.txt
[edit]