Cryptographic functions, secure random number generation, and security-related utilities for building secure applications.
Secure hash functions for data integrity verification and password hashing.
import hashlib
# Hash algorithm functions
def md5(data: bytes = b'') -> hash: ...
def sha1(data: bytes = b'') -> hash: ...
def sha224(data: bytes = b'') -> hash: ...
def sha256(data: bytes = b'') -> hash: ...
def sha384(data: bytes = b'') -> hash: ...
def sha512(data: bytes = b'') -> hash: ...
def sha3_224(data: bytes = b'') -> hash: ...
def sha3_256(data: bytes = b'') -> hash: ...
def sha3_384(data: bytes = b'') -> hash: ...
def sha3_512(data: bytes = b'') -> hash: ...
def shake_128(data: bytes = b'') -> hash: ...
def shake_256(data: bytes = b'') -> hash: ...
def blake2b(data: bytes = b'', digest_size: int = 64, key: bytes = b'',
salt: bytes = b'', person: bytes = b'', fanout: int = 1,
depth: int = 1, leaf_size: int = 0, node_offset: int = 0,
node_depth: int = 0, inner_size: int = 0, last_node: bool = False,
usedforsecurity: bool = True) -> hash: ...
def blake2s(data: bytes = b'', digest_size: int = 32, key: bytes = b'',
salt: bytes = b'', person: bytes = b'', fanout: int = 1,
depth: int = 1, leaf_size: int = 0, node_offset: int = 0,
node_depth: int = 0, inner_size: int = 0, last_node: bool = False,
usedforsecurity: bool = True) -> hash: ...
# Generic hash constructor
def new(name: str, data: bytes = b'', usedforsecurity: bool = True) -> hash: ...
# Password-based key derivation
def pbkdf2_hmac(hash_name: str, password: bytes, salt: bytes, iterations: int,
dklen: int = None) -> bytes: ...
def scrypt(password: bytes, salt: bytes, n: int, r: int, p: int,
maxmem: int = 0, dklen: int = 64) -> bytes: ...
# Utility functions
def algorithms_guaranteed() -> set: ...
def algorithms_available() -> set: ...
# Hash object interface
class hash:
@property
def digest_size(self) -> int: ...
@property
def block_size(self) -> int: ...
@property
def name(self) -> str: ...
def update(self, data: bytes) -> None: ...
def digest(self) -> bytes: ...
def hexdigest(self) -> str: ...
def copy(self) -> hash: ...
# SHAKE hash objects (variable length output)
class shake:
def digest(self, length: int) -> bytes: ...
def hexdigest(self, length: int) -> str: ...
def update(self, data: bytes) -> None: ...
def copy(self) -> shake: ...Message authentication using cryptographic hash functions.
import hmac
# HMAC functions
def new(key: bytes, msg: bytes = None, digestmod: str = 'md5') -> HMAC: ...
def digest(key: bytes, msg: bytes, digest: str) -> bytes: ...
def compare_digest(a: bytes, b: bytes) -> bool: ...
# HMAC object
class HMAC:
def __init__(self, key: bytes, msg: bytes = None, digestmod: str = 'md5') -> None: ...
def update(self, msg: bytes) -> None: ...
def digest(self) -> bytes: ...
def hexdigest(self) -> str: ...
def copy(self) -> HMAC: ...
@property
def digest_size(self) -> int: ...
@property
def block_size(self) -> int: ...
@property
def name(self) -> str: ...Cryptographically secure random number generation for security-sensitive applications.
import secrets
# Random bytes
def token_bytes(nbytes: int = None) -> bytes: ...
def token_hex(nbytes: int = None) -> str: ...
def token_urlsafe(nbytes: int = None) -> str: ...
# Random choice
def choice(sequence): ...
def randbelow(exclusive_upper_bound: int) -> int: ...
def randbits(k: int) -> int: ...
# System random number generator
class SystemRandom:
def random(self) -> float: ...
def uniform(self, a: float, b: float) -> float: ...
def triangular(self, low: float = 0.0, high: float = 1.0, mode: float = None) -> float: ...
def betavariate(self, alpha: float, beta: float) -> float: ...
def expovariate(self, lambd: float) -> float: ...
def gammavariate(self, alpha: float, beta: float) -> float: ...
def gauss(self, mu: float, sigma: float) -> float: ...
def lognormvariate(self, mu: float, sigma: float) -> float: ...
def normalvariate(self, mu: float, sigma: float) -> float: ...
def vonmisesvariate(self, mu: float, kappa: float) -> float: ...
def paretovariate(self, alpha: float) -> float: ...
def weibullvariate(self, alpha: float, beta: float) -> float: ...
def getrandbits(self, k: int) -> int: ...
def randrange(self, start: int, stop: int = None, step: int = 1) -> int: ...
def randint(self, a: int, b: int) -> int: ...
def choice(self, seq): ...
def choices(self, population, weights=None, cum_weights=None, k: int = 1) -> list: ...
def shuffle(self, x, random=None) -> None: ...
def sample(self, population, k: int, counts=None) -> list: ...
# Default instance
default_rng: SystemRandomSecure password input and handling utilities.
import getpass
# Password input
def getpass(prompt: str = 'Password: ', stream=None) -> str: ...
def getuser() -> str: ...
# Fallback password input
def fallback_getpass(prompt: str = 'Password: ', stream=None) -> str: ...SSL/TLS security configuration and certificate handling (extended from networking).
import ssl
# Certificate verification functions
def match_hostname(cert: dict, hostname: str) -> None: ...
def cert_time_to_seconds(cert_time: str) -> int: ...
def get_server_certificate(addr: tuple, ssl_version=None, ca_certs=None,
timeout=None) -> str: ...
# Certificate store management
def get_default_verify_paths() -> DefaultVerifyPaths: ...
def enum_certificates(store_name: str): ...
def enum_crls(store_name: str): ...
# Protocol and cipher information
def get_protocol_name(version_info: int) -> str: ...
def cipher_to_string(cipher_suite: tuple) -> str: ...
# Security policy
class SSLContext:
# Security options
@property
def options(self) -> int: ...
@options.setter
def options(self, value: int) -> None: ...
@property
def minimum_version(self): ...
@minimum_version.setter
def minimum_version(self, value) -> None: ...
@property
def maximum_version(self): ...
@maximum_version.setter
def maximum_version(self, value) -> None: ...
@property
def security_level(self) -> int: ...
# Certificate chain verification
def get_ca_certs(self, binary_form: bool = False) -> list: ...
def get_ciphers(self) -> list: ...
# Certificate store paths
class DefaultVerifyPaths:
cafile: str # Path to CA bundle file
capath: str # Path to CA directory
openssl_cafile_env: str # Environment variable for CA file
openssl_cafile: str # OpenSSL default CA file
openssl_capath_env: str # Environment variable for CA path
openssl_capath: str # OpenSSL default CA path
# SSL/TLS options
OP_NO_SSLv2: int # Disable SSL v2
OP_NO_SSLv3: int # Disable SSL v3
OP_NO_TLSv1: int # Disable TLS v1.0
OP_NO_TLSv1_1: int # Disable TLS v1.1
OP_NO_TLSv1_2: int # Disable TLS v1.2
OP_NO_TLSv1_3: int # Disable TLS v1.3
OP_CIPHER_SERVER_PREFERENCE: int # Use server cipher order
OP_SINGLE_DH_USE: int # Generate new DH key for each handshake
OP_SINGLE_ECDH_USE: int # Generate new ECDH key for each handshake
OP_NO_COMPRESSION: int # Disable SSL/TLS compression
# Verification modes
VERIFY_DEFAULT: int # Default verification
VERIFY_CRL_CHECK_LEAF: int # Check CRL for leaf certificate
VERIFY_CRL_CHECK_CHAIN: int # Check CRL for entire chain
VERIFY_X509_STRICT: int # Strict X.509 compliance
VERIFY_X509_TRUSTED_FIRST: int # Use trusted certificates first
# Alert descriptions
ALERT_DESCRIPTION_CLOSE_NOTIFY: int
ALERT_DESCRIPTION_UNEXPECTED_MESSAGE: int
ALERT_DESCRIPTION_BAD_RECORD_MAC: int
ALERT_DESCRIPTION_RECORD_OVERFLOW: int
ALERT_DESCRIPTION_HANDSHAKE_FAILURE: int
ALERT_DESCRIPTION_BAD_CERTIFICATE: int
ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: int
ALERT_DESCRIPTION_CERTIFICATE_REVOKED: int
ALERT_DESCRIPTION_CERTIFICATE_EXPIRED: int
ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: int
ALERT_DESCRIPTION_ILLEGAL_PARAMETER: int
ALERT_DESCRIPTION_UNKNOWN_CA: int
ALERT_DESCRIPTION_ACCESS_DENIED: int
ALERT_DESCRIPTION_DECODE_ERROR: int
ALERT_DESCRIPTION_DECRYPT_ERROR: int
ALERT_DESCRIPTION_PROTOCOL_VERSION: int
ALERT_DESCRIPTION_INSUFFICIENT_SECURITY: int
ALERT_DESCRIPTION_INTERNAL_ERROR: int
ALERT_DESCRIPTION_USER_CANCELLED: int
ALERT_DESCRIPTION_NO_RENEGOTIATION: int
ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: intFunctions for sanitizing and validating input data for security.
import html
import xml.sax.saxutils
# HTML escaping
def escape(s: str, quote: bool = True) -> str: ...
def unescape(s: str) -> str: ...
# XML escaping
def escape(data: str, entities: dict = None) -> str: ...
def unescape(data: str, entities: dict = None) -> str: ...
def quoteattr(data: str, entities: dict = None) -> str: ...
# URL-safe encoding (from urllib.parse)
import urllib.parse
def quote(string: str, safe: str = '/', encoding=None, errors=None) -> str: ...
def quote_plus(string: str, safe: str = '', encoding=None, errors=None) -> str: ...
def unquote(string: str, encoding: str = 'utf-8', errors: str = 'replace') -> str: ...
def unquote_plus(string: str, encoding: str = 'utf-8', errors: str = 'replace') -> str: ...Important cryptographic constants and utility functions.
# Common hash digest sizes (in bytes)
MD5_DIGEST_SIZE: int = 16
SHA1_DIGEST_SIZE: int = 20
SHA224_DIGEST_SIZE: int = 28
SHA256_DIGEST_SIZE: int = 32
SHA384_DIGEST_SIZE: int = 48
SHA512_DIGEST_SIZE: int = 64
# Secure comparison of sensitive data
def compare_digest(a: str | bytes, b: str | bytes) -> bool: ...
# Timing-safe string comparison
def secrets_compare_digest(a: str | bytes, b: str | bytes) -> bool: ...import secrets
# Generate secure random token for sessions
session_token = secrets.token_urlsafe(32)
# Generate secure random password
import string
alphabet = string.ascii_letters + string.digits + "!@#$%^&*"
password = ''.join(secrets.choice(alphabet) for _ in range(12))
# Generate secure random salt for password hashing
salt = secrets.token_bytes(16)import hashlib
import secrets
def hash_password(password: str) -> tuple[bytes, bytes]:
"""Hash password with secure salt."""
salt = secrets.token_bytes(16)
password_hash = hashlib.pbkdf2_hmac('sha256',
password.encode('utf-8'),
salt,
100000) # 100k iterations
return password_hash, salt
def verify_password(password: str, password_hash: bytes, salt: bytes) -> bool:
"""Verify password against hash."""
computed_hash = hashlib.pbkdf2_hmac('sha256',
password.encode('utf-8'),
salt,
100000)
return secrets.compare_digest(password_hash, computed_hash)import hashlib
import hmac
def calculate_file_hash(filepath: str) -> str:
"""Calculate SHA-256 hash of file."""
sha256_hash = hashlib.sha256()
with open(filepath, "rb") as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256_hash.update(chunk)
return sha256_hash.hexdigest()
def verify_message_integrity(message: bytes, key: bytes, received_mac: bytes) -> bool:
"""Verify message integrity using HMAC."""
computed_mac = hmac.new(key, message, hashlib.sha256).digest()
return hmac.compare_digest(computed_mac, received_mac)# Hash algorithm names
HashAlgorithm = str # 'md5', 'sha1', 'sha256', 'sha512', etc.
# Hash digest representations
HashDigest = bytes # Binary hash digest
HexDigest = str # Hexadecimal hash digest
# Key derivation parameters
KDFParams = dict[str, int | bytes] # Parameters for key derivation functions# Certificate information
Certificate = dict[str, object] # X.509 certificate as dictionary
# Cipher suite information
CipherSuite = tuple[str, str, int] # (name, protocol, secret_bits)
# SSL/TLS versions
SSLVersion = int # SSL/TLS protocol version constant
# Certificate verification result
VerificationResult = dict[str, object] # Certificate verification details# Security tokens
SecurityToken = str | bytes # Authentication/session tokens
# Cryptographic keys
CryptoKey = bytes # Cryptographic key material
# Random data
SecureBytes = bytes # Cryptographically secure random bytes# Password representations
Password = str # Plain text password (handle securely!)
PasswordHash = bytes # Hashed password
Salt = bytes # Cryptographic salt
# Authentication credentials
Credentials = tuple[str, str] # (username, password)