← Back to Articles
Application Security Cryptography Key Management TLS/SSL Backend Engineering Cybersecurity

Public Key Cryptography in Production: RSA, ECC, TLS, and Key Management Best Practices

Textbook cryptography rarely survives contact with production. Learn how to properly implement public/private key encryption, master Envelope Encryption, secure your keys in KMS/Vault, and understand modern TLS and Post-Quantum Cryptography.

July 2026
20 min read
Written by Engineering Team

Introduction: The "Data Too Long" Exception That Exposed Our Flawed Crypto

Early in my career, I was tasked with encrypting user PII (Personally Identifiable Information) before storing it in the database. I generated an RSA-2048 key pair, wrote a quick wrapper around RSA.Encrypt(), and deployed it. It worked perfectly in testing. Then, a user uploaded a 2MB PDF containing their tax documents. The application crashed with a CryptographicException: Data too long for key.

I had fallen for the most common trap in applied cryptography: trying to use asymmetric encryption (RSA) for bulk data encryption. Furthermore, I was using outdated padding schemes that left us vulnerable to padding oracle attacks. Cryptography is not just about choosing the right algorithm; it is about understanding the operational realities of key management, performance, and modern threat models. This guide bridges the gap between textbook theory and production reality.

Public and Private Key Encryption Flow
Asymmetric cryptography relies on mathematical trapdoor functions, but its real power lies in secure key exchange, not bulk data encryption.

Symmetric vs. Asymmetric: The Real Trade-Offs

Developers often ask, "Which one should I use?" The answer is almost always "Both, but for different things."

Feature Symmetric (AES) Asymmetric (RSA/ECC)
Key Structure Single shared secret key Mathematically linked Public/Private pair
Performance Extremely fast (hardware accelerated) Computationally heavy (100x-1000x slower)
Max Data Size Unlimited (streaming supported) Limited to key size minus padding overhead
Primary Use Case Encrypting bulk data (files, DB columns) Key exchange, Digital Signatures, Identity
Key Distribution Hard (requires secure channel) Easy (public key can be shared openly)

💡 The Golden Rule of Applied Crypto

Never use RSA to encrypt the actual payload. Use RSA to encrypt a temporary, randomly generated Symmetric (AES) key. This pattern is called Envelope Encryption.

Envelope Encryption: The Production Standard

Envelope Encryption solves the size and performance limits of RSA. You generate a unique Data Encryption Key (DEK) for every piece of data, encrypt the data with the DEK (using AES), and then encrypt the DEK with your RSA Public Key (the Key Encryption Key, or KEK).

EnvelopeEncryption.cs
csharp
              public class EnvelopeEncryptor
{
    private readonly RSA _publicKeyRsa;

    public EnvelopeEncryptor(RSA publicKeyRsa)
    {
        _publicKeyRsa = publicKeyRsa;
    }

    public (byte[] EncryptedData, byte[] EncryptedKey) Encrypt(byte[] plaintextData)
    {
        // 1. Generate an ephemeral AES-256 key (The DEK)
        using var aes = Aes.Create();
        aes.KeySize = 256;
        aes.Mode = CipherMode.GCM; // CRITICAL: Always use Authenticated Encryption (AEAD)
        aes.GenerateKey();
        aes.GenerateIV();

        // 2. Encrypt the bulk data with the AES key
        using var encryptor = aes.CreateEncryptor();
        byte[] encryptedData = encryptor.TransformFinalBlock(plaintextData, 0, plaintextData.Length);

        // 3. Encrypt the AES key with the RSA Public Key (The KEK)
        byte[] encryptedKey = _publicKeyRsa.Encrypt(
            aes.Key,
            RSAEncryptionPadding.OaepSHA256); // CRITICAL: Never use Pkcs1v1.5

        return (encryptedData, encryptedKey);
    }
}

            

Why AES-GCM? Notice the use of CipherMode.GCM. Standard AES-CBC only provides confidentiality. AES-GCM provides Authenticated Encryption with Associated Data (AEAD), ensuring the data hasn't been tampered with. Without authentication, you are vulnerable to Padding Oracle Attacks.

Digital Signatures: Proving Identity and Integrity

While encryption protects confidentiality (hiding data), digital signatures protect authenticity (proving who sent it) and integrity (proving it wasn't altered). This is the mechanism behind JWTs (JSON Web Tokens), code signing, and SSL certificates.

Concept Encryption Digital Signature
Goal Confidentiality Authenticity & Integrity
Key Used to Process Recipient's Public Key Sender's Private Key
Key Used to Verify/Decrypt Recipient's Private Key Sender's Public Key
Real-World Example Sending a secure email Verifying a software update or JWT
DigitalSignature.cs
csharp
              public byte[] SignData(byte[] data, RSA privateKey)
{
    // CRITICAL: Always sign the HASH of the data, not the raw data.
    // SHA-256 is the current minimum standard.
    return privateKey.SignData(
        data,
        HashAlgorithmName.SHA256,
        RSASignaturePadding.Pss); // PSS is preferred over Pkcs1 for new applications
}

            

How TLS 1.3 Actually Secures Your Connection

When you visit an HTTPS site, TLS 1.3 (the current standard) performs a highly optimized handshake. It no longer uses RSA for the key exchange due to the lack of Perfect Forward Secrecy (PFS).

  • Client Hello: The client sends supported cipher suites and a random number.

  • Server Hello & Certificate: The server sends its certificate (containing its public key) and selects the cipher suite.

  • Ephemeral Key Exchange (ECDHE): Both parties generate temporary Elliptic Curve keys. They exchange public values and compute a shared "Pre-Master Secret".

  • Perfect Forward Secrecy: Because the ECDHE keys are ephemeral (deleted after the session), even if the server's long-term RSA private key is stolen later, past sessions cannot be decrypted.

  • Symmetric Encryption: The Pre-Master Secret is used to derive the session keys for AES-GCM, securing the rest of the connection.

TLS 1.3 Handshake Flow
TLS 1.3 uses Ephemeral Diffie-Hellman (ECDHE) for key exchange, ensuring Perfect Forward Secrecy.

Key Management: Where Most Breaches Happen

The strongest algorithm in the world is useless if your private key is stored in a GitHub repository or a plaintext config file. In production, key management is more important than algorithm selection.

Solution Best For Pros & Cons
Cloud KMS (AWS/Azure/GCP) Cloud-native applications Pros: Highly available, automated rotation. Cons: Vendor lock-in.
HashiCorp Vault Multi-cloud / On-premise Pros: Open source, dynamic secrets. Cons: High operational overhead to manage the Vault cluster.
Hardware Security Modules (HSM) Banking, Healthcare, Root CAs Pros: Physical tamper resistance, FIPS 140-2 compliance. Cons: Very expensive.
Environment Variables Local development only Pros: Easy. Cons: Terrible for production. Easily leaked in logs or CI/CD.

💡 Key Rotation Pro Tip

Design your system to support key rotation from day one. If you hardcode a key ID in your database schema, rotating keys will require a massive data migration. Store the Key ID or Version alongside the encrypted data.

RSA vs. ECC: Choosing the Right Asymmetric Algorithm

RSA has been the standard for decades, but Elliptic Curve Cryptography (ECC) is now the preferred choice for new applications.

Feature RSA (2048-bit) ECC (P-256 / secp256r1)
Security Level Equivalent to 112-bit symmetric Equivalent to 128-bit symmetric
Key Size 256 bytes 32 bytes (8x smaller)
Performance Slower signing/encryption Much faster, uses less CPU/Battery
Recommendation Legacy systems, specific compliance All new applications, mobile, IoT

Note on RSA Key Sizes: If you must use RSA, 1024-bit is completely broken. 2048-bit is the absolute minimum, but NIST recommends transitioning to 3072-bit or 4096-bit for long-term security.

The Future: Post-Quantum Cryptography (PQC)

As of 2026, quantum computing is no longer just a theoretical threat. While large-scale, fault-tolerant quantum computers capable of breaking RSA and ECC (via Shor's algorithm) are not yet mainstream, "Store Now, Decrypt Later" attacks are a real concern for highly sensitive, long-lived data.

NIST has finalized Post-Quantum Cryptography standards (such as ML-KEM for key encapsulation and ML-DSA for digital signatures). Modern applications handling data that must remain secret for 10+ years (e.g., genomic data, state secrets) should begin implementing hybrid key exchange (combining ECDHE with ML-KEM) to future-proof their architecture.

Critical Security Mistakes to Avoid

  • Storing private keys in source control: Even in private repos. Use a secret manager.

  • Using ECB mode for AES: Electronic Codebook mode leaks patterns in the data. Always use CBC, CTR, or preferably GCM.

  • Hardcoding Initialization Vectors (IVs): The IV must be cryptographically random and unique for every encryption operation.

  • Confusing Hashing with Encryption: Hashing (SHA-256) is one-way and used for passwords (with salt). Encryption is two-way and used for data.

  • Implementing your own crypto: Never write your own encryption algorithm or protocol. Use standard, audited libraries (like Bouncy Castle or the built-in .NET System.Security.Cryptography).

  • Ignoring Certificate Pinning in Mobile Apps: Relying solely on the OS certificate store leaves mobile apps vulnerable to corporate proxies and malicious root certificates.

"Amateurs focus on the encryption algorithm. Professionals focus on key management, side-channel attacks, and proper implementation."

Frequently Asked Questions

Can I use RSA to encrypt a large file directly?
No. RSA can only encrypt data smaller than the key size minus the padding overhead (e.g., RSA-2048 with OAEP can only encrypt ~190 bytes). For files, you must use Envelope Encryption (AES for the file, RSA for the AES key).
Why is Perfect Forward Secrecy (PFS) important?
Without PFS, if an attacker records your encrypted traffic today and steals your server's private key next year, they can decrypt all past traffic. PFS ensures that every session uses a unique, ephemeral key, so a stolen long-term key only compromises future sessions, not past ones.
Should I use RSA or ECC for new projects?
Use ECC (specifically the P-256 or P-384 curves). It provides equivalent or better security than RSA with significantly smaller key sizes and faster performance, which is critical for mobile and high-throughput servers.
How do I securely store a private key in a .NET application?
Never store it in a file or config. Use the OS-level key store (Windows CAPI/CNG Key Store, macOS Keychain) or, preferably, a cloud Key Management Service (AWS KMS, Azure Key Vault) where the private key never leaves the secure hardware boundary.

Conclusion

Public key cryptography is the bedrock of digital trust, but its power is easily neutralized by poor implementation. By leveraging Envelope Encryption for bulk data, enforcing Perfect Forward Secrecy in TLS, utilizing Hardware Security Modules for key management, and transitioning to modern algorithms like ECC and Post-Quantum standards, developers can build systems that are resilient against both current and future threats.

Ready to secure your infrastructure? Explore our deep dives into [Implementing Zero Trust Architecture], [Securing .NET APIs with JWT and OAuth2], and [A Practical Guide to HashiCorp Vault] to complete your security posture.

We use cookies to improve your experience.