Typing stubs for pyOpenSSL

24.1.0.20240722 · active · verified Sun Apr 05

This is a PEP 561 type stub package for the pyOpenSSL library. It allows type-checking tools like mypy, pyright, and PyCharm to analyze code that uses pyOpenSSL. The current version, 24.1.0.20240722, aims to provide accurate annotations for `pyOpenSSL==24.1.*`. Maintained within Typeshed, updates to these stubs are released frequently, typically up to once a day.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `types-pyopenssl` by creating a self-signed certificate and private key, showcasing type annotations for common `pyOpenSSL` objects like `PKey` and `X509`. Type checkers would use these stubs to validate the types in such code.

from OpenSSL import crypto, SSL
from datetime import datetime, timedelta

def generate_self_signed_cert(
    common_name: str,
    country: str,
    state: str,
    city: str,
    organization: str,
    email: str,
    valid_days: int = 365,
) -> tuple[crypto.PKey, crypto.X509]:
    """
    Generates a self-signed certificate and private key objects with type hints.
    This demonstrates common pyOpenSSL types like PKey and X509.
    """
    # Generate a new key pair
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)

    # Create a self-signed cert
    cert = crypto.X509()
    cert.get_subject().C = country
    cert.get_subject().ST = state
    cert.get_subject().L = city
    cert.get_subject().O = organization
    cert.get_subject().CN = common_name
    cert.get_subject().emailAddress = email
    cert.set_serial_number(1000)
    # Dates must be in UTC. Format 'YYYYMMDDHHMMSSZ'
    cert.gmtime_before = (datetime.utcnow() - timedelta(days=1)).strftime('%Y%m%d%H%M%SZ')
    cert.gmtime_after = (datetime.utcnow() + timedelta(days=valid_days)).strftime('%Y%m%d%H%M%SZ')
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')

    return k, cert

# Example usage with type-hinted variables
private_key: crypto.PKey
certificate: crypto.X509
private_key, certificate = generate_self_signed_cert(
    common_name="example.com",
    country="US",
    state="CA",
    city="San Francisco",
    organization="Example Org",
    email="admin@example.com"
)

print("Generated private key and certificate objects with type hints.")
print(f"Certificate subject CN: {certificate.get_subject().CN}")
print(f"Private key type: {private_key.type()}")

view raw JSON →