RSA Key Pair Generator

Generate 2048-bit and 4096-bit RSA public and private key pairs formatted as SPKI and PKCS#8 PEM blocks.

4.9 / 5· 148 verified ratings
•
100% Client-Side Privacy
•
Verified 2026 Engine
Loading tool engine...
Frequently Used With:Base64 Encoder & Decoder →MD5 Hash Generator →JWT Decoder →HMAC Signature Generator →
Institutional-Grade Accuracy & Client-Side Privacy Guarantee

Unlike conventional calculator sites that send your financial numbers, payload data, or code snippets across remote web servers, Affi-Chain processes all mathematical derivations, algorithms, and data parsing 100% locally within your browser sandbox. No tracking cookies, no server-side retention, and zero transmission lag.

Cryptographic Foundations & Number Theory of RSA

The RSA Cryptosystem (invented in 1977 by Ron Rivest, Adi Shamir, and Leonard Adleman) represents the cornerstone of modern asymmetric public-key cryptography. It establishes secure key exchange, encrypted digital communications, and non-repudiation digital signatures across protocols including Transport Layer Security (TLS 1.2/1.3), Secure Shell (SSH-2), Pretty Good Privacy (PGP/GPG), and X.509 Public Key Infrastructure (PKI).

+---------------------------------------------------------------------------------------------------+
|                                  THE RSA ASYMMETRIC KEY LIFECYCLE                                |
+---------------------------------------------------------------------------------------------------+
|  PRIME GENERATION            MODULUS & TOTIENT               KEY EXPONENTS                        |
|  p, q: Probable Primes  -->  n = p * q                  -->  Public Exponent: e = 65537           |
|  (Miller-Rabin tested)       λ(n) = lcm(p-1, q-1)            Private Exponent: d ≡ e⁻¹ mod λ(n)  |
+---------------------------------------------------------------------------------------------------+
                                           |
                                           v
+---------------------------------------------------------------------------------------------------+
|  PUBLIC KEY (n, e)                                           PRIVATE KEY (n, d, p, q, dP, dQ, qInv)|
|  - Published globally in SPKI format                        - Stored confidentially in PKCS#8     |
|  - Encrypts session keys (OAEP)                             - Decrypts ciphertexts via CRT        |
|  - Verifies digital signatures                              - Creates non-repudiation signatures  |
+---------------------------------------------------------------------------------------------------+

The Integer Factorization Trapdoor Function

The security of RSA rests upon a fundamental mathematical asymmetry: one-way trapdoor functions.

  1. Given two 1024-bit prime integers $p$ and $q$, computing their product $n = p \times q$ requires less than a microsecond of CPU time on consumer hardware.
  2. Conversely, given only the composite modulus $n$, determining the original constituent factors $p$ and $q$ (the Integer Factorization Problem) is computationally infeasible using the most efficient known classical algorithm, the General Number Field Sieve (GNFS), which requires sub-exponential time:

$$\mathcal{O}\left( \exp\left( \left(\sqrt[3]{\frac{64}{9}} + o(1)\right) (\ln n)^{1/3} (\ln \ln n)^{2/3} \right) \right)$$

For a 2048-bit modulus, factoring requires evaluating an integer of 617 decimal digits, demanding millions of core-years of classical compute.


Mathematical Specification & Key Generation Mechanics

1. Prime Selection & Primality Verification

Cryptographically secure pseudorandom number generators (CSPRNG, such as /dev/urandom or hardware RNG instructions like RDRAND) generate random odd bitstreams of length $k/2$ (e.g., 1024 bits for RSA-2048). Candidates are tested using the Miller-Rabin Primality Test across $k \ge 64$ independent bases to guarantee a false positive probability bounded by $4^{-k} \le 2^{-128}$.

2. Carmichael's Totient vs. Euler's Totient

Historically, Euler's totient function was utilized:

$$\phi(n) = (p - 1)(q - 1)$$

Modern implementations use Carmichael's totient function $\lambda(n)$, which produces the smallest universal exponent for the multiplicative group modulo $n$:

$$\lambda(n) = \text{lcm}(p - 1, q - 1) = \frac{(p - 1)(q - 1)}{\gcd(p - 1, q - 1)}$$

3. Public Exponent Selection ($e$)

The public exponent $e$ must satisfy $1 < e < \lambda(n)$ and be coprime to $\lambda(n)$ ($\gcd(e, \lambda(n)) = 1$). Industry standards enforce $e = 65537$ ($2^{16} + 1$, also known as Fermat number $F_4$). In binary representation (0b10000000000000001), $65537$ contains exactly two set bits, allowing modular exponentiation ($c \equiv m^e \pmod n$) to complete in just 17 multiplications using the square-and-multiply algorithm while defending against low-exponent attacks.

4. Modular Multiplicative Inverse ($d$)

The private exponent $d$ is derived using the Extended Euclidean Algorithm:

$$d \equiv e^{-1} \pmod{\lambda(n)} \iff e \cdot d \equiv 1 \pmod{\lambda(n)}$$

5. Chinese Remainder Theorem (CRT) Optimization

To accelerate private key decryption and signature generation by up to $4\times$, production private keys do not evaluate $m \equiv c^d \pmod n$ directly. Instead, they compute intermediate residues using precomputed CRT coefficients:

$$dP = d \pmod{p - 1}$$ $$dQ = d \pmod{q - 1}$$ $$q_{\text{inv}} = q^{-1} \pmod p$$

The decrypted message is reconstructed via:

$$m_1 = c^{dP} \pmod p, \quad m_2 = c^{dQ} \pmod q$$ $$h = q_{\text{inv}} \times (m_1 - m_2) \pmod p$$ $$m = m_2 + h \times q$$


Key Syntax, Structure & ASN.1 Encoding Matrix

RSA keys are structured as Abstract Syntax Notation One (ASN.1) definitions and encoded into binary DER (Distinguished Encoding Rules) before being serialized into base64-armored PEM files.

+---------------------------------------------------------------------------------------------------+
|                                     ASN.1 STRUCTURE COMPARISON                                    |
+---------------------------------------------------------------------------------------------------+
|  PKCS#1 (Traditional RSA-Only)                  PKCS#8 / SPKI (Universal Cryptographic Container) |
|  - Encapsulates raw RSA components directly    - Includes AlgorithmIdentifier OID (1.2.840.113549)|
|  - Header: -----BEGIN RSA PRIVATE KEY-----      - Supports modern encryption schemes (PBKDF2/AES) |
|  - Syntax: RSAPrivateKey SEQUENCE               - Header: -----BEGIN PRIVATE KEY-----             |
+---------------------------------------------------------------------------------------------------+

ASN.1 Data Structures

-- RFC 8017: PKCS#1 v2.2 RSAPrivateKey
RSAPrivateKey ::= SEQUENCE {
    version           INTEGER,  -- 0 for two-prime RSA
    modulus           INTEGER,  -- n
    publicExponent    INTEGER,  -- e
    privateExponent   INTEGER,  -- d
    prime1            INTEGER,  -- p
    prime2            INTEGER,  -- q
    exponent1         INTEGER,  -- d mod (p-1)
    exponent2         INTEGER,  -- d mod (q-1)
    coefficient       INTEGER   -- (inverse of q) mod p
}

-- RFC 5208: PKCS#8 OneAsymmetricKey / PrivateKeyInfo
PrivateKeyInfo ::= SEQUENCE {
    version           INTEGER,
    privateKeyAlgorithm AlgorithmIdentifier,
    privateKey        OCTET STRING, -- Encapsulates RSAPrivateKey
    attributes        [0] IMPLICIT Attributes OPTIONAL
}

-- RFC 5280: SubjectPublicKeyInfo (SPKI)
SubjectPublicKeyInfo ::= SEQUENCE {
    algorithm         AlgorithmIdentifier, -- rsaEncryption OID 1.2.840.113549.1.1.1
    subjectPublicKey  BIT STRING          -- Encapsulates RSAPublicKey (n, e)
}

Production Code Implementation

Python: Industrial RSA Generation, Key Serialization & OAEP Encryption

#!/usr/bin/env python3
"""
Production RSA Key Generator and Asymmetric OAEP Encryption Engine
Utilizing the Python Cryptography Hazmat Abstraction.
"""

from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes, serialization
from typing import Tuple


class RSAKeyManager:
    @staticmethod
    def generate_keypair(key_size: int = 2048, public_exponent: int = 65537) -> Tuple[str, str]:
        """
        Generates an RSA keypair and serializes to PEM format.
        Private key: PKCS#8 format.
        Public key: X.509 SubjectPublicKeyInfo (SPKI) format.
        """
        if key_size < 2048:
            raise ValueError("Key sizes below 2048 bits are cryptographically insecure.")

        # Cryptographically secure prime generation and key synthesis
        private_key = rsa.generate_private_key(
            public_exponent=public_exponent,
            key_size=key_size,
        )

        # Serialize Private Key (PKCS#8 PEM)
        pem_private = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption(),
        ).decode("utf-8")

        # Serialize Public Key (SPKI PEM)
        public_key = private_key.public_key()
        pem_public = public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo,
        ).decode("utf-8")

        return pem_private, pem_public

    @staticmethod
    def encrypt_oaep(pem_public: str, plaintext: bytes) -> bytes:
        """
        Encrypts arbitrary payload using RSA-OAEP with SHA-256 and MGF1.
        Prevents Bleichenbacher padding oracle vulnerabilities.
        """
        public_key = serialization.load_pem_public_key(pem_public.encode("utf-8"))
        ciphertext = public_key.encrypt(
            plaintext,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None,
            ),
        )
        return ciphertext

    @staticmethod
    def decrypt_oaep(pem_private: str, ciphertext: bytes) -> bytes:
        """
        Decrypts an RSA-OAEP ciphertext using the private key.
        """
        private_key = serialization.load_pem_private_key(
            pem_private.encode("utf-8"),
            password=None,
        )
        plaintext = private_key.decrypt(
            ciphertext,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA256()),
                algorithm=hashes.SHA256(),
                label=None,
            ),
        )
        return plaintext


# Demonstration
if __name__ == "__main__":
    priv_pem, pub_pem = RSAKeyManager.generate_keypair(key_size=2048)
    print("--- GENERATED PKCS#8 PRIVATE KEY (TRUNCATED) ---")
    print("\n".join(priv_pem.splitlines()[:5]) + "\n...[SNIP]...\n" + priv_pem.splitlines()[-1])

    print("\n--- GENERATED SPKI PUBLIC KEY ---")
    print(pub_pem.strip())

    secret_message = b"Cryptographic security parameter: alpha=0.001"
    encrypted_blob = RSAKeyManager.encrypt_oaep(pub_pem, secret_message)
    decrypted_message = RSAKeyManager.decrypt_oaep(priv_pem, encrypted_blob)

    assert secret_message == decrypted_message
    print(f"\nOAEP Decryption verified: {decrypted_message.decode('utf-8')}")

TypeScript: Native Node.js Key Generation and Export

import { generateKeyPairSync, publicEncrypt, privateDecrypt, constants } from "crypto";

export interface KeyPairPEM {
  publicKeyPem: string;
  privateKeyPem: string;
}

export function generateRSAKeyPair(modulusBits: 2048 | 3072 | 4096 = 2048): KeyPairPEM {
  const { publicKey, privateKey } = generateKeyPairSync("rsa", {
    modulusLength: modulusBits,
    publicKeyEncoding: {
      type: "spki",
      format: "pem",
    },
    privateKeyEncoding: {
      type: "pkcs8",
      format: "pem",
    },
  });

  return {
    publicKeyPem: publicKey,
    privateKeyPem: privateKey,
  };
}

export function encryptWithOAEP(publicKeyPem: string, data: Buffer): Buffer {
  return publicEncrypt(
    {
      key: publicKeyPem,
      padding: constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: "sha256",
    },
    data
  );
}

export function decryptWithOAEP(privateKeyPem: string, ciphertext: Buffer): Buffer {
  return privateDecrypt(
    {
      key: privateKeyPem,
      padding: constants.RSA_PKCS1_OAEP_PADDING,
      oaepHash: "sha256",
    },
    ciphertext
  );
}

Cryptographic Algorithm Comparison Matrix

AlgorithmKey Size (Bits)NIST Security Level (Bits)Public Key SizeSignature SizeSigning SpeedQuantum Resilience (Shor's)
RSA-20482048112~294 bytes256 bytesSlowBroken
RSA-40964096128~550 bytes512 bytesVery SlowBroken
ECDSA (P-256)25612865 bytes (uncompressed)64 bytesModerateBroken
Ed25519 (EdDSA)25612832 bytes64 bytesUltra FastBroken
ML-KEM (Kyber-768)N/A (Lattice)128 (Post-Quantum)1,184 bytesN/A (Key Encapsulation)Ultra FastResistant
ML-DSA (Dilithium-3)N/A (Lattice)128 (Post-Quantum)1,952 bytes3,293 bytesFastResistant

Critical Vulnerabilities, Pitfalls & Edge Cases

1. The Catastrophe of Textbook RSA

In introductory mathematics, RSA encryption is defined as $c \equiv m^e \pmod n$. In actual security engineering, Textbook RSA is completely broken:

  • Deterministic Malleability: If an attacker observes $c_1 \equiv m_1^e$ and $c_2 \equiv m_2^e$, they can multiply the ciphertexts: $c_1 \cdot c_2 \equiv (m_1 \cdot m_2)^e \pmod n$.
  • Small Root Attacks (Coppersmith's Theorem): If $e = 3$ and message $m$ is small such that $m^3 < n$, the modulus never wraps around. An attacker calculates $m = \sqrt[3]{c}$ over real integers without needing to factor $n$.

2. Bleichenbacher's Million Message Oracle Attack on PKCS#1 v1.5

PKCS#1 v1.5 padding formats data as 0x00 || 0x02 || PS || 0x00 || M. In 1998, Daniel Bleichenbacher discovered that if an SSL/TLS server decrypts an RSA ciphertext and returns a distinct error message when the decrypted plaintext fails to start with 0x00 0x02, the server acts as an adaptive chosen-ciphertext oracle. By sending thousands of carefully crafted ciphertexts, an adversary can recover the full plaintext in hours without knowing the private key.

Remediation: Never deploy PKCS#1 v1.5 padding in new architectures. Enforce RSA-OAEP (Optimal Asymmetric Encryption Padding) for encryption and RSA-PSS (Probabilistic Signature Scheme) for signatures.

3. Weak Entropy and Prime Generation Collisions

If prime selection relies on an inadequately seeded pseudorandom generator (such as the infamous Debian OpenSSL CVE-2008-0166 disaster or embedded IoT device keygen bugs):

  • Two distinct entities generated keys with $n_1 = p \times q_1$ and $n_2 = p \times q_2$ that share a single common prime factor $p$.
  • Computing $\gcd(n_1, n_2)$ using Euclid's algorithm takes milliseconds, immediately factoring both keys and recovering both private exponents.

4. Fermat Factorization for Proximate Primes

If primes $p$ and $q$ are chosen too close to each other (e.g., $|p - q| < 2 \cdot n^{1/4}$):

  • Fermat's factorization method expresses $n$ as the difference of two squares: $n = a^2 - b^2 = (a - b)(a + b)$.
  • A solver searching integers $a \ge \lceil\sqrt{n}\rceil$ will discover integer $b = \sqrt{a^2 - n}$ in minimal iterations, instantly yielding factors $p$ and $q$. Cryptographic RNGs must ensure $|p - q| > 2^{k/2 - 100}$.

Frequently Asked Questions

Should I use 2048-bit or 4096-bit RSA keys?
2048-bit RSA is the global industry standard balancing security and performance. 4096-bit is recommended for long-term root certificate authorities.

Explore Related Utilities