Python wrapper module around the OpenSSL library providing cryptographic functionality and TLS/SSL capabilities
—
Asymmetric key operations supporting RSA, DSA, EC, Ed25519, and Ed448 keys with generation, loading, serialization, and conversion capabilities.
Complete asymmetric key handling with support for multiple key types and cryptographic operations.
class PKey:
def __init__(self):
"""Create new empty key object"""
def generate_key(self, type: int, bits: int) -> None:
"""
Generate key pair.
Parameters:
- type: Key type (TYPE_RSA, TYPE_DSA)
- bits: Key size in bits (1024, 2048, 4096, etc.)
"""
def check(self) -> bool:
"""
Verify RSA private key consistency.
Returns:
True if key is valid, raises exception if invalid
"""
def type(self) -> int:
"""
Get key type.
Returns:
Key type constant (TYPE_RSA, TYPE_DSA, etc.)
"""
def bits(self) -> int:
"""
Get key size in bits.
Returns:
Key size (1024, 2048, 4096, etc.)
"""
def to_cryptography_key(self):
"""
Convert to cryptography library key object.
Returns:
cryptography private or public key object
"""
@classmethod
def from_cryptography_key(cls, crypto_key):
"""
Create PKey from cryptography library key.
Parameters:
- crypto_key: cryptography private or public key
Returns:
New PKey object
"""Functions for loading keys from various sources and serializing to different formats with optional encryption.
def load_privatekey(type: int, buffer: str | bytes, passphrase=None) -> PKey:
"""
Load private key from buffer.
Parameters:
- type: Format type (FILETYPE_PEM, FILETYPE_ASN1)
- buffer: Key data as string or bytes
- passphrase: Optional passphrase (str, bytes, or callable)
Returns:
PKey object containing private key
"""
def dump_privatekey(type: int, pkey: PKey, cipher=None, passphrase=None) -> bytes:
"""
Export private key to buffer.
Parameters:
- type: Output format (FILETYPE_PEM, FILETYPE_ASN1)
- pkey: Private key to export
- cipher: Optional encryption cipher (e.g., 'aes256')
- passphrase: Optional passphrase for encryption
Returns:
Private key data as bytes
"""
def load_publickey(type: int, buffer: str | bytes) -> PKey:
"""
Load public key from buffer.
Parameters:
- type: Format type (FILETYPE_PEM, FILETYPE_ASN1)
- buffer: Key data as string or bytes
Returns:
PKey object containing public key
"""
def dump_publickey(type: int, pkey: PKey) -> bytes:
"""
Export public key to buffer.
Parameters:
- type: Output format (FILETYPE_PEM, FILETYPE_ASN1)
- pkey: Public key to export
Returns:
Public key data as bytes
"""Constants identifying different asymmetric key algorithms.
TYPE_RSA: int # RSA key type
TYPE_DSA: int # DSA key typefrom OpenSSL import crypto
# Generate 2048-bit RSA key pair
key = crypto.PKey()
key.generate_key(crypto.TYPE_RSA, 2048)
print(f"Generated {key.bits()}-bit RSA key")
print(f"Key type: {key.type()}")
# Verify key consistency
if key.check():
print("Key is valid")
# Save private key with encryption
private_key_data = crypto.dump_privatekey(
crypto.FILETYPE_PEM,
key,
cipher='aes256',
passphrase=b'secretpassword'
)
with open('private_key.pem', 'wb') as f:
f.write(private_key_data)
# Save public key
public_key_data = crypto.dump_publickey(crypto.FILETYPE_PEM, key)
with open('public_key.pem', 'wb') as f:
f.write(public_key_data)from OpenSSL import crypto
# Load encrypted private key with passphrase
with open('private_key.pem', 'rb') as f:
key_data = f.read()
# Method 1: Passphrase as string
private_key = crypto.load_privatekey(
crypto.FILETYPE_PEM,
key_data,
passphrase='secretpassword'
)
# Method 2: Passphrase callback function
def get_passphrase():
return input("Enter passphrase: ").encode()
private_key = crypto.load_privatekey(
crypto.FILETYPE_PEM,
key_data,
passphrase=get_passphrase
)
print(f"Loaded {private_key.bits()}-bit key")from OpenSSL import crypto
# Generate DSA key pair
dsa_key = crypto.PKey()
dsa_key.generate_key(crypto.TYPE_DSA, 2048)
print(f"Generated {dsa_key.bits()}-bit DSA key")
# DSA keys cannot use check() method (RSA-specific)
try:
dsa_key.check()
except crypto.Error as e:
print("DSA key check not supported")
# Export DSA key
dsa_private = crypto.dump_privatekey(crypto.FILETYPE_PEM, dsa_key)
dsa_public = crypto.dump_publickey(crypto.FILETYPE_PEM, dsa_key)from OpenSSL import crypto
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
# Generate key with cryptography library
crypto_private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
# Convert to pyOpenSSL
pyopenssl_key = crypto.PKey.from_cryptography_key(crypto_private_key)
print(f"Converted key: {pyopenssl_key.bits()} bits")
# Convert back to cryptography
converted_back = pyopenssl_key.to_cryptography_key()
# Use cryptography library features
pem_data = converted_back.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
print("Key converted successfully between libraries")from OpenSSL import crypto
# Load certificate
with open('certificate.pem', 'rb') as f:
cert_data = f.read()
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_data)
# Extract public key from certificate
public_key = cert.get_pubkey()
print(f"Certificate public key: {public_key.bits()} bits")
print(f"Key type: {public_key.type()}")
# Export public key
public_key_pem = crypto.dump_publickey(crypto.FILETYPE_PEM, public_key)
with open('extracted_public_key.pem', 'wb') as f:
f.write(public_key_pem)from OpenSSL import crypto
# Load PEM key
with open('key.pem', 'rb') as f:
pem_data = f.read()
key = crypto.load_privatekey(crypto.FILETYPE_PEM, pem_data)
# Convert to DER format
der_data = crypto.dump_privatekey(crypto.FILETYPE_ASN1, key)
with open('key.der', 'wb') as f:
f.write(der_data)
# Load DER key back
with open('key.der', 'rb') as f:
der_data = f.read()
key_from_der = crypto.load_privatekey(crypto.FILETYPE_ASN1, der_data)
print("Key conversion successful")
print(f"Key size: {key_from_der.bits()} bits")from OpenSSL import crypto
# Generate CA key
ca_key = crypto.PKey()
ca_key.generate_key(crypto.TYPE_RSA, 4096)
# Create CA certificate
ca_cert = crypto.X509()
ca_cert.set_version(2)
ca_cert.set_serial_number(1)
# Set CA subject
ca_subject = ca_cert.get_subject()
ca_subject.CN = "My CA"
ca_subject.O = "My Organization"
ca_cert.set_issuer(ca_subject)
ca_cert.set_pubkey(ca_key)
# Set validity
ca_cert.gmtime_adj_notBefore(0)
ca_cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60) # 10 years
# Self-sign CA certificate
ca_cert.sign(ca_key, 'sha256')
# Generate server key
server_key = crypto.PKey()
server_key.generate_key(crypto.TYPE_RSA, 2048)
# Create server certificate
server_cert = crypto.X509()
server_cert.set_version(2)
server_cert.set_serial_number(2)
# Set server subject
server_subject = server_cert.get_subject()
server_subject.CN = "example.com"
server_cert.set_issuer(ca_subject) # Issued by CA
server_cert.set_pubkey(server_key)
# Set validity
server_cert.gmtime_adj_notBefore(0)
server_cert.gmtime_adj_notAfter(365 * 24 * 60 * 60) # 1 year
# Sign server certificate with CA key
server_cert.sign(ca_key, 'sha256')
print("Certificate chain created successfully")Install with Tessl CLI
npx tessl i tessl/pypi-pyopenssl