secrets

The secrets library provides functions for generating cryptographically strong random numbers suitable for managing secrets such as account authentication tokens, API keys, and passwords, similar to Python’s secrets module. Use it instead of random any time the output needs to be unpredictable.

Available Functions

Function Description
token_bytes(nbytes=32) Generate a random byte sequence.
token_hex(nbytes=32) Generate a random hex string.
token_urlsafe(nbytes=32) Generate a random URL-safe string.
randbelow(n) Random integer in the range [0, n).
randbits(k) Random integer with k random bits.
choice(sequence) Random element from a sequence.
compare_digest(a, b) Constant-time string comparison.

Functions

token_bytes(nbytes=32)

Generate a random byte sequence.

Parameters:

  • nbytes (int, optional): Number of bytes to generate. Default: 32.

Returns: list: integers (0-255) representing the generated bytes.

import secrets

b = secrets.token_bytes(16)
# [142, 87, 203, 45, ...]

token_hex(nbytes=32)

Generate a random text string in hexadecimal.

Parameters:

  • nbytes (int, optional): Number of random bytes; the output string is twice this length. Default: 32.

Returns: str: a hexadecimal string.

import secrets

token = secrets.token_hex(16)
# "8e57cb2d3f1a9b4c..."  (32 characters)

token_urlsafe(nbytes=32)

Generate a random URL-safe text string.

Parameters:

  • nbytes (int, optional): Number of random bytes. Default: 32.

Returns: str: a URL-safe base64-encoded string.

import secrets

token = secrets.token_urlsafe(16)
# "jlfB2t8xqbQ..."

randbelow(n)

Generate a random integer in the range [0, n).

Parameters:

  • n (int): Exclusive upper bound. Must be positive.

Returns: int: a random integer from 0 to n - 1.

Raises: Error: if n is not positive.

import secrets

dice = secrets.randbelow(6) + 1  # Random 1-6

randbits(k)

Generate a random integer with k random bits.

Parameters:

  • k (int): Number of random bits. Must be positive.

Returns: int: a random integer with k bits.

Raises: Error: if k is not positive.

import secrets

random_int = secrets.randbits(8)  # 0-255

choice(sequence)

Return a cryptographically random element from a non-empty sequence (list or string).

Parameters:

  • sequence (list/str): Non-empty sequence to choose from.

Returns: the chosen element: str if sequence is a string, otherwise the element type from the list.

Raises: Error: if sequence is empty.

import secrets

winner = secrets.choice(["Alice", "Bob", "Charlie"])
char = secrets.choice("abcdef")

compare_digest(a, b)

Compare two strings using constant-time comparison to prevent timing attacks.

Parameters:

  • a (str): First string.
  • b (str): Second string.

Returns: bool: True if the strings are equal, False otherwise.

import secrets

# Secure comparison of secret values
is_valid = secrets.compare_digest(user_token, stored_token)

When to Use

Use secrets instead of random when:

  • Generating tokens, keys, or passwords.
  • Creating nonces or salts.
  • Building any cryptographic or security-sensitive feature.
  • Protecting against prediction attacks.

Use random when performance matters more than unpredictability, or for non-security applications like games and simulations.

Python Compatibility

This library implements Python’s secrets module:

Function Supported
token_bytes Yes
token_hex Yes
token_urlsafe Yes
randbelow Yes
randbits Yes
choice Yes
compare_digest Yes
SystemRandom class No

See Also