CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-rsa

Pure-Python RSA implementation for encryption, decryption, signing, and verification

Pending
Overview
Eval results
Files

key-management.mddocs/

Key Management

RSA key pair generation and key object management including loading/saving keys in various formats and key manipulation operations.

Capabilities

Key Generation

Generate RSA key pairs with customizable parameters for security and performance requirements.

def newkeys(nbits: int, accurate: bool = True, poolsize: int = 1, exponent: int = 65537) -> Tuple[PublicKey, PrivateKey]:
    """
    Generates public and private keys, and returns them as (pub, priv).

    Parameters:
    - nbits: int - the number of bits required to store n = p*q
    - accurate: bool - when True, n will have exactly the number of bits specified (slower)
    - poolsize: int - number of processes to use for prime generation (>=1)
    - exponent: int - the exponent for the key (default 65537)

    Returns:
    Tuple[PublicKey, PrivateKey] - Generated key pair
    """

Usage Example:

import rsa

# Generate 2048-bit key pair (recommended for security)
(public_key, private_key) = rsa.newkeys(2048)

# Generate 1024-bit key pair with parallel processing
(pub, priv) = rsa.newkeys(1024, poolsize=4)

# Generate key pair with custom exponent
(pub, priv) = rsa.newkeys(2048, exponent=3)

PublicKey Class

Represents an RSA public key with methods for loading, saving, and manipulating public key data.

class PublicKey:
    def __init__(self, n: int, e: int):
        """
        Create a PublicKey instance.
        
        Parameters:
        - n: int - the RSA modulus
        - e: int - the public exponent
        """
        
    @classmethod
    def load_pkcs1(cls, keyfile: bytes, format: str = "PEM") -> 'PublicKey':
        """
        Load a public key from PKCS#1 PEM or DER format.
        
        Parameters:
        - keyfile: bytes - encoded public key data
        - format: str - key format, either "PEM" (default) or "DER"
        
        Returns:
        PublicKey - loaded public key instance
        """
        
    @classmethod
    def load_pkcs1_openssl_pem(cls, keyfile: bytes) -> 'PublicKey':
        """
        Load a public key from OpenSSL PEM format.
        
        Parameters:
        - keyfile: bytes - OpenSSL PEM-encoded public key data
        
        Returns:
        PublicKey - loaded public key instance
        """
        
    @classmethod
    def load_pkcs1_openssl_der(cls, keyfile: bytes) -> 'PublicKey':
        """
        Load a public key from OpenSSL DER format.
        
        Parameters:
        - keyfile: bytes - OpenSSL DER-encoded public key data
        
        Returns:
        PublicKey - loaded public key instance
        """
        
    def save_pkcs1_pem(self) -> bytes:
        """
        Save the public key in PKCS#1 PEM format.
        
        Returns:
        bytes - PEM-encoded public key data
        """
        
    def save_pkcs1_der(self) -> bytes:
        """
        Save the public key in PKCS#1 DER format.
        
        Returns:
        bytes - DER-encoded public key data
        """
        
    def save_pkcs1_openssl_pem(self) -> bytes:
        """
        Save the public key in OpenSSL PEM format.
        
        Returns:
        bytes - OpenSSL PEM-encoded public key data
        """

Attributes:

class PublicKey:
    n: int  # RSA modulus (product of two large primes)
    e: int  # Public exponent (typically 65537)

Usage Example:

import rsa

# Create from integers
public_key = rsa.PublicKey(12345678901234567890, 65537)

# Load from PEM file
with open('public_key.pem', 'rb') as f:
    public_key = rsa.PublicKey.load_pkcs1_pem(f.read())

# Save as PEM
pem_data = public_key.save_pkcs1_pem()
with open('public_key.pem', 'wb') as f:
    f.write(pem_data)

# Save as DER
der_data = public_key.save_pkcs1_der()

PrivateKey Class

Represents an RSA private key with methods for loading, saving, and cryptographic operations including blinded operations for timing attack protection.

class PrivateKey:
    def __init__(self, n: int, e: int, d: int, p: int, q: int):
        """
        Create a PrivateKey instance.
        
        Parameters:
        - n: int - the RSA modulus  
        - e: int - the public exponent
        - d: int - the private exponent
        - p: int - first prime factor of n
        - q: int - second prime factor of n
        """
        
    @classmethod
    def load_pkcs1(cls, keyfile: bytes, format: str = "PEM") -> 'PrivateKey':
        """
        Load a private key from PKCS#1 PEM or DER format.
        
        Parameters:
        - keyfile: bytes - encoded private key data
        - format: str - key format, either "PEM" (default) or "DER"
        
        Returns:
        PrivateKey - loaded private key instance
        """
        
    def save_pkcs1_pem(self) -> bytes:
        """
        Save the private key in PKCS#1 PEM format.
        
        Returns:
        bytes - PEM-encoded private key data
        """
        
    def save_pkcs1_der(self) -> bytes:
        """
        Save the private key in PKCS#1 DER format.
        
        Returns:
        bytes - DER-encoded private key data
        """
        
    def blinded_decrypt(self, encrypted: int) -> int:
        """
        Decrypt an integer using blinding to prevent timing attacks.
        
        Parameters:
        - encrypted: int - encrypted integer value
        
        Returns:
        int - decrypted integer value
        """
        
    def blinded_encrypt(self, message: int) -> int:
        """
        Encrypt an integer using blinding.
        
        Parameters:
        - message: int - message integer value
        
        Returns:
        int - encrypted integer value
        """

Attributes:

class PrivateKey:
    n: int      # RSA modulus (same as in public key)
    e: int      # Public exponent (same as in public key)  
    d: int      # Private exponent
    p: int      # First prime factor of n
    q: int      # Second prime factor of n
    exp1: int   # d mod (p-1), for Chinese Remainder Theorem
    exp2: int   # d mod (q-1), for Chinese Remainder Theorem
    coef: int   # Inverse of q mod p, for Chinese Remainder Theorem

Usage Example:

import rsa

# Load from PEM file
with open('private_key.pem', 'rb') as f:
    private_key = rsa.PrivateKey.load_pkcs1_pem(f.read())

# Save as PEM
pem_data = private_key.save_pkcs1_pem()
with open('private_key.pem', 'wb') as f:
    f.write(pem_data)

# Access key components
print(f"Modulus: {private_key.n}")
print(f"Public exponent: {private_key.e}")
print(f"Private exponent: {private_key.d}")

Error Handling

Key management operations may raise the following exceptions:

  • ValueError - Invalid key parameters or malformed key data
  • ImportError - Missing pyasn1 dependency for PEM/DER operations
  • TypeError - Incorrect parameter types

Security Considerations

  • Key Size: Use at least 2048 bits for security (4096 bits recommended for long-term use)
  • Random Number Generation: The library uses the system's secure random number generator
  • Timing Attacks: Private key operations use blinding to prevent timing-based attacks
  • Key Storage: Store private keys securely and never transmit them over insecure channels

Install with Tessl CLI

npx tessl i tessl/pypi-rsa

docs

cli-tools.md

crypto-operations.md

index.md

key-management.md

tile.json