Python wrapper module around the OpenSSL library providing cryptographic functionality and TLS/SSL capabilities
—
Comprehensive X.509 certificate lifecycle management including creation, signing, verification, and parsing. Supports certificate extensions, distinguished names, and various encoding formats.
Complete certificate objects with support for standard X.509 fields, extensions, and cryptographic operations.
class X509:
def __init__(self):
"""Create new empty certificate"""
def get_subject(self) -> X509Name:
"""Get certificate subject name"""
def set_subject(self, subject: X509Name):
"""Set certificate subject name"""
def get_issuer(self) -> X509Name:
"""Get certificate issuer name"""
def set_issuer(self, issuer: X509Name):
"""Set certificate issuer name"""
def get_pubkey(self) -> PKey:
"""Get certificate public key"""
def set_pubkey(self, pkey: PKey):
"""Set certificate public key"""
def get_serial_number(self) -> int:
"""Get certificate serial number"""
def set_serial_number(self, serial: int):
"""Set certificate serial number"""
def get_version(self) -> int:
"""Get certificate version (0=v1, 2=v3)"""
def set_version(self, version: int):
"""Set certificate version"""
def get_notBefore(self) -> bytes:
"""Get validity start time as ASN.1 time string"""
def set_notBefore(self, when: bytes):
"""Set validity start time"""
def get_notAfter(self) -> bytes:
"""Get validity end time as ASN.1 time string"""
def set_notAfter(self, when: bytes):
"""Set validity end time"""
def gmtime_adj_notBefore(self, amount: int):
"""Adjust validity start time by seconds offset"""
def gmtime_adj_notAfter(self, amount: int):
"""Adjust validity end time by seconds offset"""
def has_expired(self) -> bool:
"""Check if certificate has expired"""
def sign(self, pkey: PKey, digest: str):
"""
Sign certificate with private key.
Parameters:
- pkey: Private key for signing
- digest: Hash algorithm ('sha256', 'sha1', etc.)
"""
def get_signature_algorithm(self) -> bytes:
"""Get signature algorithm name"""
def digest(self, digest_name: str) -> bytes:
"""Calculate certificate digest/fingerprint"""
def add_extensions(self, extensions):
"""Add list of X509Extension objects"""
def get_extension_count(self) -> int:
"""Get number of extensions"""
def get_extension(self, index: int) -> X509Extension:
"""Get extension by index"""
def to_cryptography(self):
"""Convert to cryptography.x509.Certificate"""
@classmethod
def from_cryptography(cls, crypto_cert):
"""Create from cryptography.x509.Certificate"""X.509 distinguished names with attribute access for standard fields like country, organization, and common name.
class X509Name:
def __init__(self, name: X509Name):
"""Create copy of existing X509Name"""
def hash(self) -> int:
"""Get MD5 hash of DER representation"""
def der(self) -> bytes:
"""Get DER encoding of name"""
def get_components(self) -> list:
"""
Get list of (name, value) tuples for all components.
Returns:
List of (bytes, bytes) tuples
"""
# Direct attribute access for standard fields
countryName: str # or C
stateOrProvinceName: str # or ST
localityName: str # or L
organizationName: str # or O
organizationalUnitName: str # or OU
commonName: str # or CN
emailAddress: strFunctions for loading certificates from various sources and serializing to different formats.
def load_certificate(type: int, buffer: bytes) -> X509:
"""
Load certificate from buffer.
Parameters:
- type: Format type (FILETYPE_PEM, FILETYPE_ASN1)
- buffer: Certificate data
Returns:
X509 certificate object
"""
def dump_certificate(type: int, cert: X509) -> bytes:
"""
Export certificate to buffer.
Parameters:
- type: Output format (FILETYPE_PEM, FILETYPE_ASN1, FILETYPE_TEXT)
- cert: Certificate to export
Returns:
Certificate data as bytes
"""
# File format constants
FILETYPE_PEM: int # PEM encoding (Base64 with headers)
FILETYPE_ASN1: int # ASN.1 DER binary encoding
FILETYPE_TEXT: int # Human-readable text formatX.509 v3 certificate extensions for additional certificate metadata. Note: This class is deprecated - use the cryptography library for new code.
class X509Extension:
def __init__(self, type_name: bytes, critical: bool, value: bytes, subject=None, issuer=None):
"""
Create certificate extension.
Parameters:
- type_name: Extension type (e.g., b'basicConstraints')
- critical: Whether extension is critical
- value: Extension value in OpenSSL format
- subject: Subject certificate for relative extensions
- issuer: Issuer certificate for relative extensions
"""
def get_critical(self) -> bool:
"""Check if extension is marked critical"""
def get_short_name(self) -> bytes:
"""Get extension type short name"""
def get_data(self) -> bytes:
"""Get ASN.1 encoded extension data"""Certificate signing request handling. Note: This class is deprecated - use the cryptography library for new code.
class X509Req:
def __init__(self):
"""Create new certificate signing request"""
def set_pubkey(self, pkey: PKey):
"""Set public key"""
def get_pubkey(self) -> PKey:
"""Get public key"""
def get_subject(self) -> X509Name:
"""Get subject name"""
def set_version(self, version: int):
"""Set version (must be 0)"""
def get_version(self) -> int:
"""Get version"""
def add_extensions(self, extensions):
"""Add extensions list"""
def get_extensions(self) -> list:
"""Get extensions list"""
def sign(self, pkey: PKey, digest: str):
"""Sign CSR with private key"""
def verify(self, pkey: PKey) -> bool:
"""Verify CSR signature"""
def to_cryptography(self):
"""Convert to cryptography CSR"""
@classmethod
def from_cryptography(cls, crypto_req):
"""Create from cryptography CSR"""
def load_certificate_request(type: int, buffer: bytes) -> X509Req:
"""Load CSR from buffer"""
def dump_certificate_request(type: int, req: X509Req) -> bytes:
"""Export CSR to buffer"""from OpenSSL import crypto
import datetime
# Generate key pair
key = crypto.PKey()
key.generate_key(crypto.TYPE_RSA, 2048)
# Create certificate
cert = crypto.X509()
cert.set_version(2) # Version 3
cert.set_serial_number(1000)
# Set validity period
cert.gmtime_adj_notBefore(0) # Valid from now
cert.gmtime_adj_notAfter(365 * 24 * 60 * 60) # Valid for 1 year
# Set subject and issuer (same for self-signed)
subject = cert.get_subject()
subject.countryName = "US"
subject.stateOrProvinceName = "California"
subject.localityName = "San Francisco"
subject.organizationName = "My Organization"
subject.commonName = "localhost"
cert.set_issuer(subject)
cert.set_pubkey(key)
# Sign the certificate
cert.sign(key, 'sha256')
# Save certificate and key
cert_data = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
key_data = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
with open('self_signed.crt', 'wb') as f:
f.write(cert_data)
with open('self_signed.key', 'wb') as f:
f.write(key_data)from OpenSSL import crypto
# Load certificate from file
with open('certificate.pem', 'rb') as f:
cert_data = f.read()
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
# Examine certificate properties
print("Subject:", cert.get_subject().commonName)
print("Issuer:", cert.get_issuer().commonName)
print("Serial Number:", cert.get_serial_number())
print("Version:", cert.get_version())
print("Signature Algorithm:", cert.get_signature_algorithm().decode())
# Check validity
print("Valid From:", cert.get_notBefore().decode())
print("Valid Until:", cert.get_notAfter().decode())
print("Has Expired:", cert.has_expired())
# Get certificate fingerprint
fingerprint = cert.digest('sha256')
print("SHA256 Fingerprint:", fingerprint.decode())
# Examine extensions
for i in range(cert.get_extension_count()):
ext = cert.get_extension(i)
print(f"Extension {i}: {ext.get_short_name().decode()}")from OpenSSL import crypto
# Create new certificate
cert = crypto.X509()
subject = cert.get_subject()
# Set subject fields using attribute access
subject.countryName = "US"
subject.ST = "California" # stateOrProvinceName
subject.L = "San Francisco" # localityName
subject.O = "My Organization" # organizationName
subject.OU = "IT Department" # organizationalUnitName
subject.CN = "example.com" # commonName
subject.emailAddress = "admin@example.com"
# Print all components
components = subject.get_components()
for name, value in components:
print(f"{name.decode()}: {value.decode()}")
# Get hash of distinguished name
print("Name Hash:", hex(subject.hash()))from OpenSSL import crypto
import cryptography.x509
# Load with pyOpenSSL
with open('certificate.pem', 'rb') as f:
cert_data = f.read()
pyopenssl_cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
# Convert to cryptography library
crypto_cert = pyopenssl_cert.to_cryptography()
# Use cryptography library features
print("Subject:", crypto_cert.subject.rfc4514_string())
print("Extensions:", [ext.oid._name for ext in crypto_cert.extensions])
# Convert back to pyOpenSSL
new_pyopenssl_cert = crypto.X509.from_cryptography(crypto_cert)Install with Tessl CLI
npx tessl i tessl/pypi-pyopenssl