CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pycryptodome

PyCryptodome is a self-contained Python package of low-level cryptographic primitives

Pending
Overview
Eval results
Files

public-key-cryptography.mddocs/

Public Key Cryptography

Comprehensive public key cryptography implementation supporting RSA, DSA, ECC, and ElGamal algorithms. Provides key generation, import/export, and cryptographic operations with extensive format support and security features.

Capabilities

RSA (Rivest-Shamir-Adleman)

The most widely used public key algorithm, suitable for both encryption and digital signatures with configurable key sizes and security parameters.

def generate(bits, randfunc=None, e=65537):
    """
    Generate a new RSA key pair.
    
    Parameters:
    - bits (int): Key size in bits (minimum 1024, recommended 2048+)
    - randfunc (callable): Random function (default: Crypto.Random.get_random_bytes)
    - e (int): Public exponent (default: 65537)
    
    Returns:
    RsaKey object containing both private and public key
    """

def construct(rsa_components, consistency_check=True):
    """
    Construct RSA key from mathematical components.
    
    Parameters:
    - rsa_components (tuple): (n, e) for public key or (n, e, d, p, q) for private key
    - consistency_check (bool): Verify mathematical consistency
    
    Returns:
    RsaKey object
    """

def import_key(extern_key, passphrase=None):
    """
    Import RSA key from external format.
    
    Parameters:
    - extern_key (bytes/str): Key data in PEM, DER, PKCS#1, PKCS#8, or OpenSSH format
    - passphrase (bytes/str): Password for encrypted keys
    
    Returns:
    RsaKey object
    """

class RsaKey:
    """RSA key object with cryptographic operations."""
    
    def has_private(self) -> bool:
        """Check if private key is present."""
    
    def public_key(self):
        """Extract public key component."""
    
    def export_key(self, format='PEM', **kwargs) -> bytes:
        """
        Export key in specified format.
        
        Parameters:
        - format (str): 'PEM', 'DER', 'PKCS1', 'PKCS8', 'OpenSSH'
        - passphrase (bytes): Password for private key encryption
        - protection (str): Encryption algorithm for PKCS#8
        
        Returns:
        Exported key as bytes
        """
    
    def encrypt(self, plaintext: bytes, padding) -> bytes:
        """Encrypt with public key (use PKCS1_OAEP.new() instead)."""
    
    def decrypt(self, ciphertext: bytes, padding) -> bytes:
        """Decrypt with private key (use PKCS1_OAEP.new() instead)."""
    
    def sign(self, msg_hash: bytes, padding) -> bytes:
        """Sign hash (use Signature modules instead)."""
    
    def verify(self, msg_hash: bytes, signature: bytes, padding) -> bool:
        """Verify signature (use Signature modules instead)."""
    
    # Key properties
    size_in_bits(self) -> int: """Key size in bits."""
    size_in_bytes(self) -> int: """Key size in bytes."""
    n: int  # Modulus
    e: int  # Public exponent  
    d: int  # Private exponent (private keys only)
    p: int  # First prime factor (private keys only)
    q: int  # Second prime factor (private keys only)

oid: str  # RSA algorithm OID

ECC (Elliptic Curve Cryptography)

Modern public key cryptography based on elliptic curves, providing equivalent security to RSA with smaller key sizes and better performance.

def generate(**kwargs):
    """
    Generate new ECC key pair.
    
    Parameters:
    - curve (str): Curve name ('P-256', 'P-384', 'P-521', 'secp256k1', 'Ed25519', 'Ed448', etc.)
    - randfunc (callable): Random function
    
    Returns:
    EccKey object
    """

def construct(**kwargs):
    """
    Construct ECC key from parameters.
    
    Parameters:
    - curve (str): Curve name
    - point_x (int): Public key X coordinate
    - point_y (int): Public key Y coordinate  
    - d (int): Private key scalar (optional)
    
    Returns:
    EccKey object
    """

def import_key(encoded, passphrase=None, curve_name=None):
    """
    Import ECC key from encoded format.
    
    Parameters:
    - encoded (bytes): Key in PEM, DER, SEC1, or PKCS#8 format
    - passphrase (bytes): Password for encrypted keys
    - curve_name (str): Explicit curve name if not in key data
    
    Returns:
    EccKey object
    """

class EccKey:
    """Elliptic curve key object."""
    
    def has_private(self) -> bool:
        """Check if private key is present."""
    
    def public_key(self):
        """Extract public key component."""
    
    def export_key(self, **kwargs) -> bytes:
        """
        Export key in specified format.
        
        Parameters:
        - format (str): 'PEM', 'DER', 'SEC1', 'PKCS8', 'OpenSSH'
        - use_pkcs8 (bool): Use PKCS#8 for private keys
        - passphrase (bytes): Encryption password
        
        Returns:
        Exported key as bytes
        """
    
    # Key properties
    curve: str  # Curve name
    pointQ: EccPoint  # Public key point
    d: int  # Private scalar (private keys only)

class UnsupportedEccFeature(Exception):
    """Exception for unsupported ECC features."""

DSA (Digital Signature Algorithm)

FIPS-approved algorithm designed specifically for digital signatures, based on discrete logarithm problem.

def generate(bits, randfunc=None, domain=None):
    """
    Generate new DSA key pair.
    
    Parameters:
    - bits (int): Key size in bits (1024, 2048, 3072)
    - randfunc (callable): Random function
    - domain (tuple): Optional (p, q, g) domain parameters
    
    Returns:
    DsaKey object
    """

def construct(tup, consistency_check=True):
    """
    Construct DSA key from tuple.
    
    Parameters:
    - tup (tuple): (y, g, p, q) for public key or (y, g, p, q, x) for private key
    - consistency_check (bool): Verify mathematical consistency
    
    Returns:
    DsaKey object
    """

def import_key(extern_key, passphrase=None):
    """
    Import DSA key from external format.
    
    Parameters:
    - extern_key (bytes): Key in PEM, DER, or PKCS#8 format
    - passphrase (bytes): Password for encrypted keys
    
    Returns:
    DsaKey object
    """

class DsaKey:
    """DSA key object for digital signatures."""
    
    def has_private(self) -> bool:
        """Check if private key is present."""
    
    def public_key(self):
        """Extract public key component."""
    
    def export_key(self, **kwargs) -> bytes:
        """Export key in PEM, DER, or PKCS#8 format."""
    
    # DSA parameters
    y: int  # Public key
    g: int  # Generator
    p: int  # Prime modulus
    q: int  # Prime divisor
    x: int  # Private key (private keys only)

ElGamal

Public key algorithm based on discrete logarithm problem, primarily used for encryption with probabilistic properties.

def generate(bits, randfunc):
    """
    Generate ElGamal key pair.
    
    Parameters:
    - bits (int): Key size in bits
    - randfunc (callable): Random function
    
    Returns:
    ElGamalKey object
    """

def construct(tup):
    """
    Construct ElGamal key from tuple.
    
    Parameters:
    - tup (tuple): (p, g, y) for public key or (p, g, y, x) for private key
    
    Returns:
    ElGamalKey object
    """

class ElGamalKey:
    """ElGamal key object for encryption."""
    
    def has_private(self) -> bool:
        """Check if private key is present."""
    
    def public_key(self):
        """Extract public key component."""
    
    # ElGamal parameters
    p: int  # Prime modulus
    g: int  # Generator
    y: int  # Public key
    x: int  # Private key (private keys only)

Usage Examples

RSA Key Operations

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP

# Generate RSA key pair
key = RSA.generate(2048)
public_key = key.publickey()

# Export keys
private_pem = key.export_key('PEM')
public_pem = public_key.export_key('PEM')

# Save encrypted private key
encrypted_key = key.export_key(
    format='PEM',
    passphrase='secret_password',
    pkcs=8,
    protection='PBKDF2WithHMAC-SHA1AndAES256-CBC'
)

# Import key from file
with open('private_key.pem', 'rb') as f:
    imported_key = RSA.import_key(f.read(), passphrase='secret_password')

ECC Key Operations

from Crypto.PublicKey import ECC

# Generate ECC key with P-256 curve
key = ECC.generate(curve='P-256')

# Generate Ed25519 key for signatures
ed25519_key = ECC.generate(curve='Ed25519')

# Export public key in OpenSSH format
ssh_key = key.public_key().export_key(format='OpenSSH')

# Import from SEC1 format
with open('ec_key.pem', 'rb') as f:
    imported_key = ECC.import_key(f.read())

DSA Key Operations

from Crypto.PublicKey import DSA

# Generate DSA key
key = DSA.generate(2048)

# Export in PKCS#8 format
pkcs8_key = key.export_key(format='PKCS8')

# Construct from components
reconstructed = DSA.construct((key.y, key.g, key.p, key.q, key.x))

Key Format Support

RSA Key Formats

  • PEM: ASCII-armored format with headers
  • DER: Binary ASN.1 encoding
  • PKCS#1: RSA-specific format (RSAPrivateKey/RSAPublicKey)
  • PKCS#8: Generic private key format
  • OpenSSH: OpenSSH public key format

ECC Key Formats

  • PEM/DER: Standard ASN.1 formats
  • SEC1: Elliptic curve private key format
  • PKCS#8: Generic private key format
  • OpenSSH: OpenSSH public key format (Ed25519/ECDSA)

DSA Key Formats

  • PEM/DER: Standard ASN.1 formats
  • PKCS#8: Generic private key format

Security Considerations

Key Size Recommendations

  • RSA: Minimum 2048 bits, prefer 3072+ for long-term security
  • ECC: P-256 for most applications, P-384/P-521 for higher security
  • DSA: 2048-bit L with 256-bit N for new applications

Best Practices

  • Use cryptographically secure random number generation
  • Protect private keys with strong passphrases
  • Prefer ECC over RSA for new applications (better performance/security ratio)
  • Use appropriate padding schemes (OAEP for RSA encryption, PSS for signatures)
  • Implement proper key lifecycle management

Common Key Object Interface

class KeyObjectInterface:
    """Common interface for all key objects."""
    
    def has_private(self) -> bool:
        """Check if private key component is present."""
    
    def public_key(self):
        """Extract public key component."""
    
    def export_key(self, **kwargs) -> bytes:
        """Export key in specified format."""
    
    def size_in_bits(self) -> int:
        """Key size in bits."""

Error Handling

  • ValueError: Invalid key parameters, unsupported formats, or mathematical inconsistencies
  • TypeError: Incorrect parameter types
  • UnsupportedEccFeature: ECC-specific unsupported operations
  • ImportError: Missing dependencies for specific curves or formats

Install with Tessl CLI

npx tessl i tessl/pypi-pycryptodome

docs

cryptographic-hashing.md

cryptographic-protocols.md

digital-signatures.md

index.md

input-output-operations.md

mathematical-primitives.md

public-key-cryptography.md

symmetric-encryption.md

utility-functions.md

tile.json