Cross-platform cryptographic library providing TLS sockets, asymmetric/symmetric encryption, and key operations using OS-native crypto libraries
npx @tessl/cli install tessl/pypi-oscrypto@1.3.0A compilation-free, always up-to-date Python cryptographic library that works on Windows, macOS, Linux and BSD. oscrypto leverages the operating system's native crypto libraries to provide TLS sockets, asymmetric and symmetric encryption, key generation, signing and verification, and key derivation functions without requiring a compiler.
pip install oscryptoimport oscryptoCommon imports for specific functionality:
from oscrypto import asymmetric, symmetric, tls
from oscrypto.asymmetric import PrivateKey, PublicKey, Certificate
from oscrypto.tls import TLSSocket
from oscrypto.kdf import pbkdf2import oscrypto
from oscrypto import asymmetric, tls
# Check which backend is being used
backend = oscrypto.backend()
print(f"Using {backend} backend")
# Generate an RSA key pair
public_key, private_key = asymmetric.generate_pair('rsa', bit_size=2048)
# Create a self-signed certificate
certificate = asymmetric.load_certificate(cert_data)
# Establish a TLS connection
socket = tls.TLSSocket('example.com', 443)
socket.write(b'GET / HTTP/1.1\r\nHost: example.com\r\n\r\n')
response = socket.read(1024)
socket.close()
# Symmetric encryption
from oscrypto.symmetric import aes_cbc_pkcs7_encrypt, aes_cbc_pkcs7_decrypt
key = b'sixteen byte key' # 16 bytes for AES-128
plaintext = b'This is a secret message'
ciphertext = aes_cbc_pkcs7_encrypt(key, plaintext)
decrypted = aes_cbc_pkcs7_decrypt(key, ciphertext)oscrypto automatically selects the appropriate cryptographic backend based on the operating system:
The library provides a unified API that abstracts platform differences while ensuring all operations use OS-native, automatically-updated crypto implementations.
Core system configuration for selecting cryptographic backends and FFI libraries. This allows forcing specific implementations when needed for testing or compatibility.
def backend() -> str: ...
def ffi() -> str: ...
def use_openssl(libcrypto_path: str, libssl_path: str, trust_list_path: str = None) -> None: ...
def use_winlegacy() -> None: ...
def use_ctypes() -> None: ...Comprehensive support for RSA, DSA, and ECDSA operations including key generation, loading, signing, verification, encryption, and decryption. Handles multiple key formats and certificate operations.
def generate_pair(algorithm: str, bit_size: int = None, curve: str = None) -> Tuple[PublicKey, PrivateKey]: ...
def load_private_key(source: Union[str, bytes], password: bytes = None) -> PrivateKey: ...
def load_certificate(source: Union[str, bytes]) -> Certificate: ...
def rsa_pkcs1v15_encrypt(certificate_or_public_key: Union[Certificate, PublicKey], data: bytes) -> bytes: ...
def rsa_pkcs1v15_sign(private_key: PrivateKey, data: bytes, hash_algorithm: str) -> bytes: ...Symmetric encryption and decryption using AES, DES, 3DES, RC2, and RC4 algorithms with various modes and padding schemes. All operations use OS-native implementations.
def aes_cbc_pkcs7_encrypt(key: bytes, data: bytes, iv: bytes = None) -> bytes: ...
def aes_cbc_pkcs7_decrypt(key: bytes, data: bytes, iv: bytes = None) -> bytes: ...
def des_cbc_pkcs5_encrypt(key: bytes, data: bytes, iv: bytes = None) -> bytes: ...
def rc4_encrypt(key: bytes, data: bytes) -> bytes: ...Modern TLS socket implementation with certificate verification using OS trust stores, SNI support, session reuse, and strong cipher suites. Provides secure network communications.
class TLSSocket:
def __init__(self, hostname: str, port: int, session: TLSSession = None): ...
def read(self, max_length: int) -> bytes: ...
def write(self, data: bytes) -> None: ...
def close() -> None: ...
class TLSSession:
def __init__(self, protocol: str = None, manual_validation: bool = False): ...Password-based key derivation using PBKDF1, PBKDF2, and PKCS#12 KDF. Includes automatic iteration calculation for target computation times.
def pbkdf2(hash_algorithm: str, password: bytes, salt: bytes, iterations: int, key_length: int) -> bytes: ...
def pbkdf2_iteration_calculator(hash_algorithm: str, key_length: int, target_ms: int = 100, quiet: bool = False) -> int: ...
def pkcs12_kdf(hash_algorithm: str, password: bytes, salt: bytes, iterations: int, key_length: int, id_: int) -> bytes: ...Access and export OS trust store certificates for use with OpenSSL-based code. Provides CA certificate bundles in PEM format.
def get_list() -> List[Certificate]: ...
def get_path() -> str: ...
def clear_cache() -> None: ...Cryptographic utilities including secure random number generation and constant-time comparison for security-critical operations.
def rand_bytes(length: int) -> bytes: ...
def constant_compare(a: bytes, b: bytes) -> bool: ...Parsing and handling of keys and certificates from various formats including DER, PEM, PKCS#8, and PKCS#12.
def parse_certificate(data: bytes) -> Certificate: ...
def parse_private(data: bytes) -> PrivateKey: ...
def parse_public(data: bytes) -> PublicKey: ...
def parse_pkcs12(data: bytes, password: bytes = None) -> Tuple[Certificate, PrivateKey, List[Certificate]]: ...class Certificate:
"""X.509 certificate wrapper with validation and inspection methods."""
class PrivateKey:
"""Private key wrapper supporting RSA, DSA, and ECDSA with signing and decryption methods."""
class PublicKey:
"""Public key wrapper supporting RSA, DSA, and ECDSA with verification and encryption methods."""
class TLSSocket:
"""TLS socket wrapper providing secure network communication."""
class TLSSession:
"""TLS session manager for connection reuse and configuration."""class LibraryNotFoundError(Exception):
"""Raised when trying to find a shared library."""
class SignatureError(Exception):
"""Raised when validating a signature fails."""
class AsymmetricKeyError(Exception):
"""Raised when a key is invalid or unsupported."""
class IncompleteAsymmetricKeyError(AsymmetricKeyError):
"""Raised when a key is missing necessary information."""
class CACertsError(Exception):
"""Raised when exporting CA certs from the OS trust store fails."""
class TLSError(Exception):
"""Base exception for TLS functionality."""
class TLSConnectionError(TLSError):
"""TLS connection error."""
class TLSDisconnectError(TLSConnectionError):
"""TLS disconnect error."""
class TLSGracefulDisconnectError(TLSDisconnectError):
"""TLS graceful disconnect."""
class TLSVerificationError(TLSError):
"""Server certificate verification error during TLS handshake."""