### Install PyOTP Source: https://pyauth.github.io/pyotp/index.html Install the PyOTP library using pip. ```bash pip install pyotp ``` -------------------------------- ### Generate Provisioning URI Source: https://pyauth.github.io/pyotp/_modules/pyotp/totp.html Generates a provisioning URI for OTP apps like Google Authenticator. This URI can be encoded into a QR code for easy setup. ```python import pyotp totp = pyotp.TOTP("JBSWY3DPEHPK3PXP", name="alice", issuer="Example Inc") # Generate provisioning URI uri = totp.provisioning_uri() print(uri) # Generate provisioning URI with custom name and issuer uri_custom = totp.provisioning_uri(name="bob", issuer_name="Another Corp") print(uri_custom) ``` -------------------------------- ### Generate Current OTP Source: https://pyauth.github.io/pyotp/index.html Generates the current one-time password for a given TOTP secret. This example demonstrates how to get the current OTP value to compare with a scanned QR code. ```python import pyotp totp = pyotp.TOTP("JBSWY3DPEHPK3PXP") print("Current OTP:", totp.now()) ``` -------------------------------- ### Get TOTP Timecode Source: https://pyauth.github.io/pyotp/index.html Convert a datetime object into a timecode (counter value) for TOTP generation or verification. Accepts timezone-naive or timezone-aware datetime objects. ```python totp.timecode(datetime.datetime.now()) ``` -------------------------------- ### Generate OTP for a Specific Time Source: https://pyauth.github.io/pyotp/_modules/pyotp/totp.html Generates a TOTP for a given Unix timestamp or datetime object. Useful for testing or generating OTPs for past/future times. The `time_remaining` calculation shows how to get the seconds until the current OTP expires. ```python import datetime totp = pyotp.TOTP("JBSWY3DPEHPK3PXP") # OTP for a specific Unix timestamp print(totp.at(1678886400)) # OTP for a specific datetime object now = datetime.datetime.now() print(totp.at(now)) # Time remaining until the current OTP expires time_remaining = totp.interval - datetime.datetime.now().timestamp() % totp.interval print(f"Time remaining: {time_remaining} seconds") ``` -------------------------------- ### build_uri() Source: https://pyauth.github.io/pyotp/index.html Builds a provisioning URI. ```APIDOC ## build_uri() ### Description Builds a provisioning URI. ### Method Not specified (likely a function call in Python) ### Endpoint Not applicable (Python function) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### HOTP.provisioning_uri Method Source: https://pyauth.github.io/pyotp/_modules/pyotp/hotp.html Generates the provisioning URI for the HOTP, which can be used to provision an OTP app like Google Authenticator. ```APIDOC ## HOTP.provisioning_uri Method ### Description Returns the provisioning URI for the OTP. This can then be encoded in a QR Code and used to provision an OTP app like Google Authenticator. See also: https://github.com/google/google-authenticator/wiki/Key-Uri-Format ### Parameters - **name** (Optional[str]) - Optional - name of the user account. - **initial_count** (Optional[int]) - Optional - starting HMAC counter value. Defaults to 0. - **issuer_name** (Optional[str]) - Optional - the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator. - **kwargs** - Additional keyword arguments to be passed to `utils.build_uri`. ### Returns - **str** - The provisioning URI. ``` -------------------------------- ### Build Provisioning URI for OTP Source: https://pyauth.github.io/pyotp/_modules/pyotp/utils.html Generates a provisioning URI for TOTP or HOTP, suitable for QR code generation to provision authenticator apps. Handles default and non-default parameters for algorithm, digits, and period. ```python import unicodedata from hmac import compare_digest from typing import Dict, Optional, Union from urllib.parse import quote, urlencode, urlparse [docs] def build_uri( secret: str, name: str, initial_count: Optional[int] = None, issuer: Optional[str] = None, algorithm: Optional[str] = None, digits: Optional[int] = None, period: Optional[int] = None, **kwargs, ) -> str: """ Returns the provisioning URI for the OTP; works for either TOTP or HOTP. This can then be encoded in a QR Code and used to provision the Google Authenticator app. For module-internal use. See also: https://github.com/google/google-authenticator/wiki/Key-Uri-Format :param secret: the hotp/totp secret used to generate the URI :param name: name of the account :param initial_count: starting counter value, defaults to None. If none, the OTP type will be assumed as TOTP. :param issuer: the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator :param algorithm: the algorithm used in the OTP generation. :param digits: the length of the OTP generated code. :param period: the number of seconds the OTP generator is set to expire every code. :param kwargs: other query string parameters to include in the URI :returns: provisioning uri """ # initial_count may be 0 as a valid param is_initial_count_present = initial_count is not None # Handling values different from defaults is_algorithm_set = algorithm is not None and algorithm != "sha1" is_digits_set = digits is not None and digits != 6 is_period_set = period is not None and period != 30 otp_type = "hotp" if is_initial_count_present else "totp" base_uri = "otpauth://{0}/{1}?{2}" url_args: Dict[str, Union[None, int, str]] = {"secret": secret} label = quote(name) if issuer is not None: label = quote(issuer) + ":" + label url_args["issuer"] = issuer if is_initial_count_present: url_args["counter"] = initial_count if is_algorithm_set: url_args["algorithm"] = algorithm.upper() # type: ignore if is_digits_set: url_args["digits"] = digits if is_period_set: url_args["period"] = period for k, v in kwargs.items(): if not isinstance(v, str): raise ValueError("All otpauth uri parameters must be strings") if k == "image": image_uri = urlparse(v) if image_uri.scheme != "https" or not image_uri.netloc or not image_uri.path: raise ValueError("{} is not a valid url".format(image_uri)) url_args[k] = v uri = base_uri.format(otp_type, label, urlencode(url_args).replace("+", "%20")) return uri ``` -------------------------------- ### Build Provisioning URI for TOTP or HOTP Source: https://pyauth.github.io/pyotp/index.html Build a provisioning URI for either TOTP or HOTP. This utility function is primarily for internal use and can configure various OTP parameters. ```python pyotp.utils.build_uri(secret="JBSWY3DPEHPK3PXP", name="alice@google.com", issuer="Example") ``` -------------------------------- ### Generate HOTP Provisioning URI Source: https://pyauth.github.io/pyotp/_modules/pyotp/hotp.html Creates a provisioning URI for an HOTP, suitable for QR code generation to provision authenticator apps. It includes parameters like name, initial count, issuer, algorithm, and digits. ```python def provisioning_uri( self, name: Optional[str] = None, initial_count: Optional[int] = None, issuer_name: Optional[str] = None, **kwargs, ) -> str: """ Returns the provisioning URI for the OTP. This can then be encoded in a QR Code and used to provision an OTP app like Google Authenticator. See also: https://github.com/google/google-authenticator/wiki/Key-Uri-Format :param name: name of the user account :param initial_count: starting HMAC counter value, defaults to 0 :param issuer_name: the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator :returns: provisioning URI """ return utils.build_uri( self.secret, name=name if name else self.name, initial_count=initial_count if initial_count else self.initial_count, issuer=issuer_name if issuer_name else self.issuer, algorithm=self.digest().name, digits=self.digits, **kwargs, ) ``` -------------------------------- ### Parse OTP Provisioning URI Source: https://pyauth.github.io/pyotp/index.html Parses a provisioning URI string to create a PyOTP TOTP or HOTP object. This is useful for reading OTP configurations from a URI. ```python pyotp.parse_uri('otpauth://totp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App') ``` ```text >>> ``` ```python pyotp.parse_uri('otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0' ``` ```text >>> ``` -------------------------------- ### pyotp.utils.build_uri Source: https://pyauth.github.io/pyotp/index.html Builds a provisioning URI for either TOTP or HOTP. This URI can be used to provision OTP apps like Google Authenticator. ```APIDOC ## pyotp.utils.build_uri ### Description Returns the provisioning URI for the OTP; works for either TOTP or HOTP. This can then be encoded in a QR Code and used to provision the Google Authenticator app. ### Parameters * **secret** (str) - the hotp/totp secret used to generate the URI * **name** (str) - name of the account * **initial_count** (int | None) - starting counter value, defaults to None. If none, the OTP type will be assumed as TOTP. * **issuer** (str | None) - the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator * **algorithm** (str | None) - the algorithm used in the OTP generation. * **digits** (int | None) - the length of the OTP generated code. * **period** (int | None) - the number of seconds the OTP generator is set to expire every code. * **kwargs** - other query string parameters to include in the URI. ### Returns str - provisioning uri ``` -------------------------------- ### parse_uri() Source: https://pyauth.github.io/pyotp/index.html Parses a provisioning URI into its components. ```APIDOC ## parse_uri() ### Description Parses a provisioning URI into its components. ### Method Not specified (likely a function call in Python) ### Endpoint Not applicable (Python function) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### HOTP Class Initialization Source: https://pyauth.github.io/pyotp/_modules/pyotp/hotp.html Initializes an HOTP object with a secret key and optional parameters like digits, digest algorithm, account name, issuer, and initial counter value. ```APIDOC ## HOTP Class ### Description Handler for HMAC-based OTP counters. ### `__init__` Method #### Parameters - **s** (str) - Required - secret in base32 format - **digits** (int) - Optional - number of integers in the OTP. Defaults to 6. - **digest** (Any) - Optional - digest function to use in the HMAC (expected to be SHA1). Defaults to `hashlib.sha1`. - **name** (Optional[str]) - Optional - account name. - **issuer** (Optional[str]) - Optional - issuer. - **initial_count** (int) - Optional - starting HMAC counter value. Defaults to 0. ``` -------------------------------- ### build_uri() Source: https://pyauth.github.io/pyotp/index.html Builds a provisioning URI for a given secret, type, issuer, and name. ```APIDOC ## build_uri() ### Description Constructs a provisioning URI that can be used to set up OTP secrets in authenticator applications. ### Method Not applicable (Python function) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pyotp secret = 'base32secret3232' name = 'user@example.com' issuer = 'MyIssuer' # For TOTP totp_uri = pyotp.build_uri(secret, name=name, issuer_name=issuer) print(f"TOTP URI: {totp_uri}") # For HOTP hotp_uri = pyotp.build_uri(secret, name=name, issuer_name=issuer, otp_type='hotp') print(f"HOTP URI: {hotp_uri}") ``` ### Response #### Success Response Returns a string representing the provisioning URI. #### Response Example ``` otpauth://totp/MyIssuer:user@example.com?secret=base32secret3232&issuer=MyIssuer otpauth://hotp/MyIssuer:user@example.com?secret=base32secret3232&issuer=MyIssuer ``` ``` -------------------------------- ### Generate HOTP Provisioning URI Source: https://pyauth.github.io/pyotp/index.html Generates a provisioning URI for an HOTP secret, including an initial counter value. This is used for counter-based OTPs compatible with Google Authenticator. ```python pyotp.hotp.HOTP('JBSWY3DPEHPK3PXP').provisioning_uri(name="alice@google.com", issuer_name="Secure App", initial_count=0) ``` ```text >>> 'otpauth://hotp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App&counter=0' ``` -------------------------------- ### HOTP Initialization Source: https://pyauth.github.io/pyotp/_modules/pyotp/hotp.html Initializes an HOTP object with a secret, digits, digest, name, issuer, and initial count. The digest defaults to SHA1 if not provided. ```python import hashlib from typing import Any, Optional from . import utils from .otp import OTP class HOTP(OTP): """ Handler for HMAC-based OTP counters. """ def __init__( self, s: str, digits: int = 6, digest: Any = None, name: Optional[str] = None, issuer: Optional[str] = None, initial_count: int = 0, ) -> None: """ :param s: secret in base32 format :param initial_count: starting HMAC counter value, defaults to 0 :param digits: number of integers in the OTP. Some apps expect this to be 6 digits, others support more. :param digest: digest function to use in the HMAC (expected to be SHA1) :param name: account name :param issuer: issuer """ if digest is None: digest = hashlib.sha1 self.initial_count = initial_count super().__init__(s=s, digits=digits, digest=digest, name=name, issuer=issuer) ``` -------------------------------- ### Counter-based OTPs (HOTP) Source: https://pyauth.github.io/pyotp/index.html Generate and verify counter-based one-time passwords using the HOTP class. The `at()` method generates an OTP for a specific counter value, and `verify()` checks if a given OTP matches the expected value for a counter. ```python import pyotp hotp = pyotp.HOTP('base32secret3232') hotp.at(0) # => '260182' hotp.at(1) # => '055283' hotp.at(1401) # => '316439' # OTP verified with a counter hotp.verify('316439', 1401) # => True hotp.verify('316439', 1402) # => False ``` -------------------------------- ### Verify OTP with Validity Window Source: https://pyauth.github.io/pyotp/_modules/pyotp/totp.html Verifies a given OTP against the current time, with an optional validity window. This allows for a grace period before and after the exact timecode. ```python import pyotp import datetime totp = pyotp.TOTP("JBSWY3DPEHPK3PXP") # Verify OTP for the current time print(totp.verify("123456")) # Verify OTP with a validity window of 1 (checks current, previous, and next timecode) print(totp.verify("123456", valid_window=1)) # Verify OTP at a specific time print(totp.verify("123456", for_time=datetime.datetime.now())) ``` -------------------------------- ### Steam.generate_otp() Source: https://pyauth.github.io/pyotp/index.html Generates a One-Time Password compatible with Steam Guard. ```APIDOC ## Steam.generate_otp() ### Description Generates a One-Time Password (OTP) specifically formatted for Steam Guard authentication. ### Method Not applicable (Python method) ### Endpoint Not applicable (Python method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pyotp # Steam Guard uses a 20-character base32 secret steam_secret = 'CD27576B524C43414341' steam = pyotp.Steam(steam_secret) otp = steam.generate_otp() print(f"Steam Guard OTP: {otp}") ``` ### Response #### Success Response Returns a 5-digit string representing the Steam Guard OTP. #### Response Example ``` '123456' ``` ``` -------------------------------- ### HOTP.verify Method Source: https://pyauth.github.io/pyotp/_modules/pyotp/hotp.html Verifies if a provided OTP matches the OTP generated for a specific counter. ```APIDOC ## HOTP.verify Method ### Description Verifies the OTP passed in against the current counter OTP. ### Parameters - **otp** (str) - Required - the OTP to check against. - **counter** (int) - Required - the OTP HMAC counter. ### Returns - **bool** - True if the OTP is valid for the given counter, False otherwise. ``` -------------------------------- ### HOTP.at Method Source: https://pyauth.github.io/pyotp/_modules/pyotp/hotp.html Generates the One-Time Password (OTP) for a given counter value. ```APIDOC ## HOTP.at Method ### Description Generates the OTP for the given count. ### Parameters - **count** (int) - Required - the OTP HMAC counter. ### Returns - **str** - The generated OTP. ``` -------------------------------- ### Parse OTP Provisioning URI Source: https://pyauth.github.io/pyotp/_modules/pyotp.html Parses a Google Authenticator provisioning URI for TOTP or HOTP. Supports extracting secret, issuer, algorithm, digits, period, and counter from the URI. ```python def parse_uri(uri: str) -> OTP: """ Parses the provisioning URI for the OTP; works for either TOTP or HOTP. See also: https://github.com/google/google-authenticator/wiki/Key-Uri-Format :param uri: the hotp/totp URI to parse :returns: OTP object """ # Secret (to be filled in later) secret = None # Encoder (to be filled in later) encoder = None # Digits (to be filled in later) digits = None # Data we'll parse to the correct constructor otp_data: Dict[str, Any] = {} # Parse with URLlib parsed_uri = urlparse(unquote(uri)) if parsed_uri.scheme != "otpauth": raise ValueError("Not an otpauth URI") # Parse issuer/accountname info accountinfo_parts = split(":|%3A", parsed_uri.path[1:], maxsplit=1) if len(accountinfo_parts) == 1: otp_data["name"] = accountinfo_parts[0] else: otp_data["issuer"] = accountinfo_parts[0] otp_data["name"] = accountinfo_parts[1] # Parse values for key, value in parse_qsl(parsed_uri.query): if key == "secret": secret = value elif key == "issuer": if "issuer" in otp_data and otp_data["issuer"] is not None and otp_data["issuer"] != value: raise ValueError("If issuer is specified in both label and parameters, it should be equal.") otp_data["issuer"] = value elif key == "algorithm": if value == "SHA1": otp_data["digest"] = hashlib.sha1 elif value == "SHA256": otp_data["digest"] = hashlib.sha256 elif value == "SHA512": otp_data["digest"] = hashlib.sha512 else: raise ValueError("Invalid value for algorithm, must be SHA1, SHA256 or SHA512") elif key == "encoder": encoder = value elif key == "digits": digits = int(value) otp_data["digits"] = digits elif key == "period": otp_data["interval"] = int(value) elif key == "counter": otp_data["initial_count"] = int(value) if encoder != "steam": if digits is not None and digits not in [6, 7, 8]: raise ValueError("Digits may only be 6, 7, or 8") if not secret: raise ValueError("No secret found in URI") # Create objects if encoder == "steam": return contrib.Steam(secret, **otp_data) if parsed_uri.netloc == "totp": return TOTP(secret, **otp_data) elif parsed_uri.netloc == "hotp": return HOTP(secret, **otp_data) raise ValueError("Not a supported OTP type") ``` -------------------------------- ### Generate HOTP Provisioning URI Source: https://pyauth.github.io/pyotp/index.html Generate a provisioning URI for a HMAC-based One-Time Password (HOTP) object. This URI can be used to provision an OTP app like Google Authenticator. ```python hotp.provisioning_uri(name="Jane Doe", initial_count=10, issuer_name="AnotherCompany") ``` -------------------------------- ### parse_uri() Source: https://pyauth.github.io/pyotp/index.html Parses a provisioning URI into its constituent parts (secret, issuer, and name). ```APIDOC ## parse_uri() ### Description Parses a provisioning URI into its constituent parts (secret, issuer, and name). ### Method Not applicable (Python function) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pyotp uri = "otpauth://totp/ACME%20Co:john.doe@email.com?secret=base32secret3232&issuer=ACME%20Co" secret, issuer, name = pyotp.parse_uri(uri) print(f"Secret: {secret}, Issuer: {issuer}, Name: {name}") ``` ### Response #### Success Response Returns a tuple containing the secret key, issuer, and name. #### Response Example ``` ('base32secret3232', 'ACME Co', 'john.doe@email.com') ``` ``` -------------------------------- ### TOTP Initialization Source: https://pyauth.github.io/pyotp/_modules/pyotp/totp.html Initializes a TOTP object with a base32 secret, number of digits, digest function, account name, issuer, and time interval. Defaults to SHA1 digest and a 30-second interval. ```python import pyotp import hashlib totp = pyotp.TOTP("JBSWY3DPEHPK3PXP", digits=6, digest=hashlib.sha1, name="test", issuer="test_issuer", interval=30) ``` -------------------------------- ### Generate TOTP Provisioning URI Source: https://pyauth.github.io/pyotp/index.html Generates a provisioning URI for a TOTP secret, suitable for use with Google Authenticator and other OTP apps. Requires the secret key, user name, and issuer name. ```python pyotp.totp.TOTP('JBSWY3DPEHPK3PXP').provisioning_uri(name='alice@google.com', issuer_name='Secure App') ``` ```text >>> 'otpauth://totp/Secure%20App:alice%40google.com?secret=JBSWY3DPEHPK3PXP&issuer=Secure%20App' ``` -------------------------------- ### pyotp.parse_uri Source: https://pyauth.github.io/pyotp/index.html Parses a provisioning URI for either TOTP or HOTP. This function is useful for decoding OTP configuration from a URI string. ```APIDOC ## pyotp.parse_uri ### Description Parses the provisioning URI for the OTP; works for either TOTP or HOTP. ### Parameters * **uri** (str) - the hotp/totp URI to parse ### Returns OTP object ``` -------------------------------- ### Generate TOTP Provisioning URI Source: https://pyauth.github.io/pyotp/index.html Generate a provisioning URI for a Time-based One-Time Password (TOTP) object. This URI can be used to provision an OTP app like Google Authenticator. ```python totp.provisioning_uri(name="John Doe", issuer_name="MyCompany") ``` -------------------------------- ### Time-based OTPs (TOTP) Source: https://pyauth.github.io/pyotp/index.html Generate and verify time-based one-time passwords using the TOTP class. Ensure the secret key is kept confidential and used for both generation and verification. ```python import pyotp import time totp = pyotp.TOTP('base32secret3232') totp.now() # => '492039' # OTP verified for current time totp.verify('492039') # => True time.sleep(30) totp.verify('492039') # => False ``` -------------------------------- ### strings_equal() Source: https://pyauth.github.io/pyotp/index.html Compares two strings for equality in a constant-time manner. ```APIDOC ## strings_equal() ### Description Compares two strings for equality in a constant-time manner to prevent timing attacks. ### Method Not specified (likely a function call in Python) ### Endpoint Not applicable (Python function) ### Parameters Not specified in source. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### Verify TOTP Source: https://pyauth.github.io/pyotp/index.html Verify a provided OTP against the current time-based one-time password. An optional valid_window can extend the verification period. ```python totp.verify(otp="123456") ``` -------------------------------- ### Verify HOTP Source: https://pyauth.github.io/pyotp/_modules/pyotp/hotp.html Verifies if the provided OTP matches the OTP generated for the given counter. ```python def verify(self, otp: str, counter: int) -> bool: """ Verifies the OTP passed in against the current counter OTP. :param otp: the OTP to check against :param counter: the OTP HMAC counter """ return utils.strings_equal(str(otp), str(self.at(counter))) ``` -------------------------------- ### parse_uri Source: https://pyauth.github.io/pyotp/_modules/pyotp.html Parses a Google Authenticator provisioning URI (for TOTP or HOTP) and returns an OTP object. It supports extracting secret, issuer, algorithm, digits, and period. ```APIDOC ## parse_uri ### Description Parses a provisioning URI for OTP (TOTP or HOTP) and returns an appropriate OTP object. This function can extract various parameters like secret, issuer, algorithm, digits, and period from the URI. ### Signature ```python def parse_uri(uri: str) -> OTP ``` ### Parameters * **uri** (str) - Required - The OTP provisioning URI string to parse. ### Returns * (OTP) - An OTP object (either TOTP or HOTP) representing the parsed URI. ### Raises * **ValueError**: If the URI is not an 'otpauth' scheme, if the issuer is inconsistent, if the algorithm is invalid, if the digits are invalid, if no secret is found, or if the OTP type is unsupported. ``` -------------------------------- ### Verify HOTP Source: https://pyauth.github.io/pyotp/index.html Verify a provided OTP against the HMAC-based one-time password for a specific counter. This ensures the correct OTP for the given counter value. ```python hotp.verify(otp="654321", counter=5) ``` -------------------------------- ### HOTP Class Source: https://pyauth.github.io/pyotp/index.html Provides functionality for Counter-based One-Time Passwords (HOTP). ```APIDOC ## HOTP Class ### Description Provides functionality for Counter-based One-Time Passwords (HOTP). ### Methods #### `HOTP.at(secret, counter)` Generates an HOTP code for a given counter. #### `HOTP.provisioning_uri(secret, name, issuer_name)` Generates a provisioning URI for an HOTP secret. #### `HOTP.verify(secret, otp, counter)` Verifies an HOTP code against the generated code for a given counter. ### Parameters Not specified in source beyond method arguments. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### pyotp.hotp.HOTP Source: https://pyauth.github.io/pyotp/index.html Handler for HMAC-based OTP counters. Used for generating and verifying HOTP codes. ```APIDOC ## pyotp.hotp.HOTP ### Description Handler for HMAC-based OTP counters. ### Methods #### at Generates the OTP for the given count. * **Parameters** * **count** (int) - the OTP HMAC counter * **Returns** OTP #### provisioning_uri Returns the provisioning URI for the OTP. This can then be encoded in a QR Code and used to provision an OTP app like Google Authenticator. * **Parameters** * **name** (str | None) - name of the user account * **initial_count** (int | None) - starting HMAC counter value, defaults to 0 * **issuer_name** (str | None) - the name of the OTP issuer; this will be the organization title of the OTP entry in Authenticator * **kwargs** - other query string parameters to include in the URI. * **Returns** str - provisioning URI #### verify Verifies the OTP passed in against the current counter OTP. * **Parameters** * **otp** (str) - the OTP to check against * **counter** (int) - the OTP HMAC counter * **Returns** bool - True if verification succeeded, False otherwise ``` -------------------------------- ### Generate Random Base32 Secret Key Source: https://pyauth.github.io/pyotp/index.html Generate a 32-character base32 secret key compatible with Google Authenticator and other OTP apps. ```python pyotp.random_base32() ``` -------------------------------- ### strings_equal() Source: https://pyauth.github.io/pyotp/index.html Compares two strings in a way that is resistant to timing attacks. ```APIDOC ## strings_equal() ### Description Compares two strings for equality using a constant-time comparison algorithm to mitigate timing side-channel attacks. ### Method Not applicable (Python function) ### Endpoint Not applicable (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import pyotp str1 = 'secret' str2 = 'secret' str3 = 'secret!' print(f"'{str1}' == '{str2}'? {pyotp.strings_equal(str1, str2)}") print(f"'{str1}' == '{str3}'? {pyotp.strings_equal(str1, str3)}") ``` ### Response #### Success Response Returns `True` if the strings are equal, `False` otherwise. #### Response Example ``` True False ``` ``` -------------------------------- ### pyotp.utils.strings_equal Source: https://pyauth.github.io/pyotp/index.html Performs a timing-attack resistant string comparison. ```APIDOC ## pyotp.utils.strings_equal ### Description Timing-attack resistant string comparison. Normal comparison using == will short-circuit on the first mismatching character. This avoids that by scanning the whole string, though we still reveal to a timing attack whether the strings are the same length. ### Parameters * **s1** (str) - The first string to compare. * **s2** (str) - The second string to compare. ### Returns bool - True if the strings are equal, False otherwise. ``` -------------------------------- ### Steam Class Source: https://pyauth.github.io/pyotp/index.html Provides functionality for generating Steam Guard OTP codes. ```APIDOC ## Steam Class ### Description Provides functionality for generating Steam Guard OTP codes. ### Methods #### `Steam.generate_otp(secret)` Generates a Steam Guard OTP code. ### Parameters Not specified in source beyond method arguments. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### Generate Random Hex-Encoded Secret Key Source: https://pyauth.github.io/pyotp/index.html Generate a 40-character hex-encoded secret key. This format may be required by some applications. ```python pyotp.random_hex() # returns a 40-character hex-encoded secret ``` -------------------------------- ### Generate Current Time OTP Source: https://pyauth.github.io/pyotp/_modules/pyotp/totp.html Generates the current Time-Based One-Time Password (TOTP) based on the system's current time. ```python import pyotp totp = pyotp.TOTP("JBSWY3DPEHPK3PXP") print(totp.now()) ``` -------------------------------- ### random_base32 Source: https://pyauth.github.io/pyotp/_modules/pyotp.html Generates a random Base32 encoded string suitable for OTP secrets. It enforces a minimum length of 32 characters (160 bits). ```APIDOC ## random_base32 ### Description Generates a random Base32 encoded string for OTP secrets. The function ensures a minimum length of 32 characters (160 bits) to maintain security standards. ### Signature ```python def random_base32(length: int = 32, chars: Sequence[str] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") -> str ``` ### Parameters * **length** (int) - Optional - The desired length of the random string. Defaults to 32. * **chars** (Sequence[str]) - Optional - The character set to use for generation. Defaults to uppercase Base32 characters. ### Returns * (str) - A randomly generated Base32 string. ``` -------------------------------- ### Timing-Attack Resistant String Comparison Source: https://pyauth.github.io/pyotp/index.html Compare two strings in a timing-attack resistant manner. This method avoids short-circuiting on the first mismatch, ensuring consistent execution time. ```python pyotp.utils.strings_equal(s1="abc", s2="abc") ``` -------------------------------- ### HOTP Class Source: https://pyauth.github.io/pyotp/index.html Represents a Counter-based One-Time Password (HOTP) generator and verifier. ```APIDOC ## HOTP Class ### Description Provides functionality for generating and verifying Counter-based One-Time Passwords (HOTP) according to RFC 4226. ### Methods #### `HOTP.at(self, counter)` Generates an HOTP for a specific counter value. - **counter** (int) - The counter value. #### `HOTP.provisioning_uri(self, name, issuer_name=None)` Generates a provisioning URI for an HOTP secret, which can be used to set up authenticator apps. - **name** (str) - The name of the account (e.g., email address). - **issuer_name** (str, optional) - The name of the issuer (e.g., company name). #### `HOTP.verify(self, otp, counter, drift_window=1)` Verifies a given OTP against a specific counter value, allowing for a small counter drift. - **otp** (str) - The one-time password to verify. - **counter** (int) - The expected counter value. - **drift_window** (int, optional) - The number of counters to check around the expected counter. Defaults to 1. ### Request Example (HOTP.at() and HOTP.verify()) ```python import pyotp hotp = pyotp.HOTP('base32secret3232') print(f"HOTP at counter 0: {hotp.at(0)}") print(f"HOTP at counter 1: {hotp.at(1)}") # Verify OTP if hotp.verify('316439', 1401): print("OTP is valid for counter 1401.") else: print("OTP is invalid for counter 1401.") ``` ### Response Example (HOTP.at()) ``` '260182' ``` ### Response Example (HOTP.verify()) ``` True ``` ``` -------------------------------- ### Steam.generate_otp Source: https://pyauth.github.io/pyotp/index.html Generates a Steam-specific One-Time Password (OTP) using a provided HMAC counter value. ```APIDOC ## Steam.generate_otp ### Description Generates a Steam-specific One-Time Password (OTP) using a provided HMAC counter value. ### Method This is a method of the `Steam` class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **input** (int) - Required - The HMAC counter value to use as the OTP input. Usually either the counter, or the computed integer based on the Unix timestamp ### Request Example ```json { "input": 1234567890 } ``` ### Response #### Success Response (200) - **otp** (str) - The generated One-Time Password. #### Response Example ```json { "otp": "123456" } ``` ``` -------------------------------- ### pyotp.totp.TOTP Source: https://pyauth.github.io/pyotp/index.html Handler for time-based OTP counters. Used for generating and verifying TOTP codes. ```APIDOC ## pyotp.totp.TOTP ### Description Handler for time-based OTP counters. ### Methods #### at Generates the current time OTP for a given time. * **Parameters** * **for_time** (int | datetime) - the time to generate an OTP for * **counter_offset** (int) - the amount of ticks to add to the time counter * **Returns** OTP value #### now Generate the current time OTP. * **Returns** OTP value #### provisioning_uri Returns the provisioning URI for the OTP. This can then be encoded in a QR Code and used to provision an OTP app like Google Authenticator. * **Parameters** * **name** (str | None) - Optional name for the account. * **issuer_name** (str | None) - Optional issuer name for the OTP. * **kwargs** - other query string parameters to include in the URI. * **Returns** str - The provisioning URI. #### timecode Accepts either a timezone naive or a timezone aware datetime as argument and returns the corresponding counter value (timecode). * **Parameters** * **for_time** (datetime) - The datetime object to convert to a timecode. * **Returns** int - The corresponding counter value. #### verify Verifies the OTP passed in against the current time OTP. * **Parameters** * **otp** (str) - the OTP to check against * **for_time** (datetime | None) - Time to check OTP at (defaults to now) * **valid_window** (int) - extends the validity to this many counter ticks before and after the current one * **Returns** bool - True if verification succeeded, False otherwise ``` -------------------------------- ### TOTP Class Source: https://pyauth.github.io/pyotp/_modules/pyotp/totp.html The TOTP class handles time-based OTP counters. It can be initialized with a secret, number of digits, digest algorithm, account name, issuer, and time interval. ```APIDOC ## Class TOTP ### Description Handles time-based OTP counters. It can be initialized with a secret, number of digits, digest algorithm, account name, issuer, and time interval. ### Methods #### `__init__(self, s: str, digits: int = 6, digest: Any = None, name: Optional[str] = None, issuer: Optional[str] = None, interval: int = 30)` Initializes the TOTP object. - **s** (str) - secret in base32 format - **digits** (int) - number of integers in the OTP. Defaults to 6. - **digest** (Any) - digest function to use in the HMAC (expected to be SHA1). Defaults to `hashlib.sha1`. - **name** (Optional[str]) - account name. - **issuer** (Optional[str]) - issuer. - **interval** (int) - the time interval in seconds for OTP. Defaults to 30. #### `at(self, for_time: Union[int, datetime.datetime], counter_offset: int = 0) -> str` Generates an OTP for a specific time. Accepts either a Unix timestamp integer or a datetime object. - **for_time** (Union[int, datetime.datetime]) - the time to generate an OTP for. - **counter_offset** (int) - the amount of ticks to add to the time counter. Defaults to 0. - **Returns** (str) - OTP value. #### `now(self) -> str` Generates the current time OTP. - **Returns** (str) - OTP value. #### `verify(self, otp: str, for_time: Optional[datetime.datetime] = None, valid_window: int = 0) -> bool` Verifies the OTP passed in against the current time OTP. - **otp** (str) - the OTP to check against. - **for_time** (Optional[datetime.datetime]) - Time to check OTP at (defaults to now). - **valid_window** (int) - extends the validity to this many counter ticks before and after the current one. Defaults to 0. - **Returns** (bool) - True if verification succeeded, False otherwise. #### `provisioning_uri(self, name: Optional[str] = None, issuer_name: Optional[str] = None, **kwargs) -> str` Returns the provisioning URI for the OTP. This can then be encoded in a QR Code and used to provision an OTP app like Google Authenticator. - **name** (Optional[str]) - account name. - **issuer_name** (Optional[str]) - issuer name. - **kwargs** - Additional keyword arguments to pass to `utils.build_uri`. - **Returns** (str) - The provisioning URI. #### `timecode(self, for_time: datetime.datetime) -> int` Accepts either a timezone naive or a timezone aware datetime as argument and returns the corresponding counter value (timecode). - **for_time** (datetime.datetime) - The datetime object to convert to a timecode. - **Returns** (int) - The calculated timecode. ``` -------------------------------- ### TOTP Class Source: https://pyauth.github.io/pyotp/index.html Provides functionality for Time-based One-Time Passwords (TOTP). ```APIDOC ## TOTP Class ### Description Provides functionality for Time-based One-Time Passwords (TOTP). ### Methods #### `TOTP.at(secret, drift_counter=0, t0=0, xlst=30)` Generates a TOTP code for a given time. #### `TOTP.now(secret, t0=0, xlst=30)` Generates the current TOTP code. #### `TOTP.provisioning_uri(secret, name, issuer_name)` Generates a provisioning URI for a TOTP secret. #### `TOTP.timecode(t=None, t0=0, xlst=30)` Calculates the current time step. #### `TOTP.verify(secret, otp, drift_counter=0, t0=0, xlst=30)` Verifies a TOTP code against the generated codes within a drift window. ### Parameters Not specified in source beyond method arguments. ### Request Example Not specified in source. ### Response Not specified in source. ``` -------------------------------- ### random_hex Source: https://pyauth.github.io/pyotp/_modules/pyotp.html Generates a random hexadecimal string, typically used for OTP secrets. It enforces a minimum length of 40 characters (160 bits). ```APIDOC ## random_hex ### Description Generates a random hexadecimal string suitable for OTP secrets. It enforces a minimum length of 40 characters (160 bits). ### Signature ```python def random_hex(length: int = 40, chars: Sequence[str] = "ABCDEF0123456789") -> str ``` ### Parameters * **length** (int) - Optional - The desired length of the random string. Defaults to 40. * **chars** (Sequence[str]) - Optional - The character set to use for generation. Defaults to hexadecimal characters. ### Returns * (str) - A randomly generated hexadecimal string. ``` -------------------------------- ### Generate HOTP at Specific Count Source: https://pyauth.github.io/pyotp/index.html Generate a HMAC-based One-Time Password (HOTP) for a specific counter value. This is used for HMAC-based OTPs. ```python hotp.at(count=5) ``` -------------------------------- ### Generate Random Base32 Secret Source: https://pyauth.github.io/pyotp/_modules/pyotp.html Generates a random Base32 encoded secret of a specified length. Requires a minimum length of 32 characters (160 bits). ```python import hashlib from re import split from typing import Any, Dict, Sequence from urllib.parse import parse_qsl, unquote, urlparse from . import contrib # noqa:F401 from .compat import random from .hotp import HOTP as HOTP from .otp import OTP as OTP from .totp import TOTP as TOTP def random_base32(length: int = 32, chars: Sequence[str] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") -> str: # Note: the otpauth scheme DOES NOT use base32 padding for secret lengths not divisible by 8. # Some third-party tools have bugs when dealing with such secrets. # We might consider warning the user when generating a secret of length not divisible by 8. if length < 32: raise ValueError("Secrets should be at least 160 bits") return "".join(random.choice(chars) for _ in range(length)) ``` -------------------------------- ### Generate HOTP at a Specific Count Source: https://pyauth.github.io/pyotp/_modules/pyotp/hotp.html Generates the OTP for a given counter value by adding it to the initial count. ```python def at(self, count: int) -> str: """ Generates the OTP for the given count. :param count: the OTP HMAC counter :returns: OTP """ return self.generate_otp(self.initial_count + count) ``` -------------------------------- ### Generate Random Hex Secret Source: https://pyauth.github.io/pyotp/_modules/pyotp.html Generates a random hexadecimal secret of a specified length. Requires a minimum length of 40 characters (160 bits). ```python def random_hex(length: int = 40, chars: Sequence[str] = "ABCDEF0123456789") -> str: if length < 40: raise ValueError("Secrets should be at least 160 bits") return random_base32(length=length, chars=chars) ``` -------------------------------- ### TOTP Class Source: https://pyauth.github.io/pyotp/index.html Represents a Time-based One-Time Password (TOTP) generator and verifier. ```APIDOC ## TOTP Class ### Description Provides functionality for generating and verifying Time-based One-Time Passwords (TOTP) according to RFC 6238. ### Methods #### `TOTP.at(self, current_time)` Generates a TOTP for a specific point in time. - **current_time** (int) - The current Unix timestamp. #### `TOTP.now(self)` Generates the current TOTP based on the system's current time. #### `TOTP.provisioning_uri(self, name, issuer_name=None)` Generates a provisioning URI for a TOTP secret, which can be used to set up authenticator apps. - **name** (str) - The name of the account (e.g., email address). - **issuer_name** (str, optional) - The name of the issuer (e.g., company name). #### `TOTP.timecode(self, current_time)` Calculates the time step (counter) for a given Unix timestamp. - **current_time** (int) - The current Unix timestamp. #### `TOTP.verify(self, otp, drift_window=1)` Verifies a given OTP against the current time, allowing for a small time drift. - **otp** (str) - The one-time password to verify. - **drift_window** (int, optional) - The number of time steps to check around the current time. Defaults to 1. ### Request Example (TOTP.now() and TOTP.verify()) ```python import pyotp import time totp = pyotp.TOTP('base32secret3232') print(f"Current OTP: {totp.now()}") # Verify OTP if totp.verify('492039'): print("OTP is valid.") else: print("OTP is invalid.") time.sleep(30) if totp.verify('492039'): print("OTP is valid.") else: print("OTP is invalid after 30 seconds.") ``` ### Response Example (TOTP.now()) ``` '492039' ``` ### Response Example (TOTP.verify()) ``` True ``` ```