📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Explain asymmetric cryptography with RSA and ECDSA. What is the difference between encrypting and signing with a key pair, which key sizes and curves are acceptable today, why padding such as OAEP and PSS matters, and when would you use asymmetric rather than symmetric cryptography in a .NET system?

Covers public-key cryptography in .NET: RSA vs ECDSA/ECDH, encrypt-with-public vs sign-with-private, key sizes and curves, OAEP and PSS padding versus PKCS#1 v1.5, hybrid encryption and where asymmetric keys appear in real systems.

Mid-Level Theory Intermediate cryptography digital-signatures dotnet ecdsa rsa security

🎯 Key points

  • Encrypt with the recipient's public key, decrypt with their private key; sign with your private key, verify with your public key
  • RSA-3072 for new or long-lived keys (2048 only as a legacy minimum); ECDSA P-256/P-384 gives equivalent strength at far smaller size
  • RSA encryption must use OAEP-SHA256; PKCS#1 v1.5 encryption is open to Bleichenbacher padding-oracle attacks
  • RSA signatures: PSS for new designs; PKCS#1 v1.5 (RS256) remains acceptable for interoperability
  • RSA can only encrypt about 190 bytes at 2048-bit OAEP-SHA256 (318 at 3072): use hybrid encryption with an AES key
  • Asymmetric is orders of magnitude slower than AES; use it for key exchange, signatures and identity
  • Key lifecycle: non-exportable keys in Key Vault/HSM, key ids, expiry and rotation policies
  • Quantum threat: Shor's algorithm breaks RSA and ECC; ASD advises transitioning by 2030; .NET 10 adds MLKem and MLDsa

⏱ 30-second answer

Asymmetric cryptography uses a key pair: what one key does, only the other undoes. For encryption you use the recipient's public key and only their private key decrypts. For signing you use your private key and anyone verifies with your public key, proving origin and integrity.

RSA does both: use 3072-bit keys for anything new or long-lived (2048 is only the legacy floor), OAEP-SHA256 for encryption and PSS for new signature formats. ECDSA (signing) and ECDH (key agreement) on P-256/P-384 give equivalent security with much smaller keys. Asymmetric operations are slow and RSA can only encrypt a few hundred bytes, so real systems use hybrid encryption: asymmetric to agree or wrap an AES key, AES for the data, as in TLS and Key Vault key wrapping. Keep private keys non-exportable in Key Vault/HSMs, and plan for post-quantum algorithms (ML-KEM, ML-DSA in .NET 10): ASD's guidance is to move off RSA and ECC by 2030.

🗣 Full answer (senior)

How I would answer this in an interview

"Symmetric crypto has a key-distribution problem: both sides need the same secret. Asymmetric crypto solves it with a key pair where the public key can be shared freely. The two uses run in opposite directions. To keep something confidential you encrypt with the recipient's public key, and only their private key decrypts it. To prove who sent something you sign with your private key, and anyone with your public key can verify it wasn't changed and came from you.

In .NET I use RSA.Create(3072) or ECDsa.Create(ECCurve.NamedCurves.nistP256), but in production I rarely hold private keys in process memory; they live in Key Vault or an HSM and I call sign or unwrap through the SDK. For RSA the padding is part of the security: OAEP with SHA-256 for encryption, because PKCS#1 v1.5 encryption is vulnerable to Bleichenbacher-style padding oracles, and PSS for new signature formats, though PKCS#1 v1.5 signatures like JWT's RS256 are still considered safe. For sizes I follow the ISM and NIST: RSA 2048 as the floor, 3072 for keys that live for years, and P-256 or P-384 for elliptic curves.

RSA-2048 with OAEP-SHA256 can only encrypt about 190 bytes, and it is orders of magnitude slower than AES, so I never encrypt data with it directly. I generate a random AES-256 key, encrypt the data with AES-GCM, and wrap the AES key with RSA-OAEP. That's envelope encryption, and TLS 1.3 does the equivalent with ECDHE key agreement.

The mistake I see is using asymmetric crypto where a shared secret is fine, like an internal webhook where HMAC would be simpler, or the reverse: sharing an HMAC secret with dozens of third parties when they only need to verify, which is exactly what a public key is for."


Encrypt vs sign

Encryption Signature
Goal Confidentiality Integrity, authenticity, non-repudiation
Who uses the private key Recipient (decrypts) Sender (signs)
Who uses the public key Sender (encrypts) Anyone (verifies)
RSA padding OAEP-SHA256 PSS (or PKCS#1 v1.5)
EC equivalent ECDH key agreement + AES ECDSA, EdDSA
.NET rsa.Encrypt(data, RSAEncryptionPadding.OaepSHA256) ecdsa.SignData(data, HashAlgorithmName.SHA256)

Key sizes (rough equivalence, NIST SP 800-57)

Symmetric strength RSA Elliptic curve
112-bit 2048 P-224
128-bit 3072 P-256
192-bit 7680 P-384

RSA vs ECDSA

RSA ECDSA
Key size Large Small
Sign speed Slow Fast
Verify speed Very fast Slower than RSA verify
Encryption Yes (OAEP) No (use ECDH + AES)
Pitfall Padding choice Needs a good random or deterministic nonce (RFC 6979)

Production example

We moved JWT signing for [an internal token service issuing about 3,000 tokens a second] from RS256 to ES256 with a Key Vault key. Token size dropped [from about 900 to about 600 bytes], signing CPU fell [roughly 10x], and APIs saw no difference in validation latency.

🔍 What the interviewer is checking

Checks whether the candidate understands the direction of keys for encryption vs signing, the padding and size rules, and when asymmetric crypto is the right tool.

Green flags

  • States clearly which key is used for each operation
  • Knows OAEP vs PKCS#1 v1.5 and current key sizes
  • Explains hybrid encryption and links it to TLS or Key Vault wrapping
  • Mentions keys in Key Vault/HSM and the post-quantum direction

Red flags

  • "Sign by encrypting with the private key" as an implementation
  • Encrypting large payloads with RSA
  • No awareness of padding or key size

📚 Learn in depth

1. The trapdoor idea

RSA:   pick primes p, q -> n = p*q, e = 65537, d = e^-1 mod lcm(p-1, q-1)
       encrypt: c = m^e mod n      decrypt: m = c^d mod n
       sign:    s = H(m)^d mod n   verify:  s^e mod n == H(m) (with padding)
ECC:   private key k (a number), public key K = k*G (a point on the curve)
       finding k from K is the elliptic-curve discrete log problem

Security rests on factoring (RSA) or the discrete log on a curve (ECC) being infeasible for classical computers. Shor's algorithm breaks both on a large enough quantum computer, which is why post-quantum algorithms exist.

2. Why padding is security, not formatting

"Textbook" RSA is deterministic and malleable: E(a) * E(b) = E(a*b). Padding adds randomness and structure.

  • PKCS#1 v1.5 encryption: a server that reveals whether padding was valid (error message, timing) becomes an oracle; Bleichenbacher (1998) and ROBOT (2017) decrypted data this way.
  • OAEP: randomised, with a mask generation function; provably secure under standard assumptions.
  • PSS: randomised signature padding with a security proof; PKCS#1 v1.5 signatures have no known practical break but no proof.

3. Hybrid encryption

Sender:  dek = random 32 bytes
         ct  = AES-GCM(dek, data)
         wk  = RSA-OAEP(recipientPublic, dek)     -> send (wk, nonce, ct, tag)
Receiver: dek = RSA-OAEP-Decrypt(private, wk) -> AES-GCM-Decrypt(dek, ct)

This is Key Vault's WrapKey/UnwrapKey, Azure Storage client-side encryption and S/MIME.

4. Where asymmetric keys appear in a .NET system

  • TLS certificates (ECDHE for key exchange, RSA/ECDSA certificate signatures)
  • JWT signing (RS256, PS256, ES256) with keys published as a JWKS
  • Code and package signing (NuGet, Authenticode)
  • Key Vault key wrapping for envelope encryption
  • SSH and Git commit signing

5. .NET implementation notes

RSA.Create() returns a platform implementation (CNG, OpenSSL). Use ImportFromPem/ExportSubjectPublicKeyInfoPem for keys, X509Certificate2.GetRSAPrivateKey() for certificate keys. .NET 10 adds MLKem, MLDsa and SlhDsa (FIPS 203, 204, 205) when the OS crypto library supports them (OpenSSL 3.5+ or Windows with PQC support); check IsSupported.

Try it yourself

  1. Encrypt 300 bytes with RSA-2048 OAEP-SHA256 and observe the exception; then implement hybrid encryption.
  2. Benchmark RSA.SignData (3072) vs ECDsa.SignData (P-256) vs verify for both with BenchmarkDotNet.
  3. Sign a message, change one byte, and verify.
  4. Create an RSA key in Key Vault and call CryptographyClient.WrapKey on an AES key.
  5. Check MLDsa.IsSupported on your machine and in a Linux container with OpenSSL 3.5.

💻 Code

Signing and verifying with ECDSA, and hybrid encryption with RSA-OAEP wrapping an AES-GCM key.

using System.Security.Cryptography;
using System.Text;

namespace Crypto.Asymmetric;

public static class Signatures
{
    public static void Demo()
    {
        using var signer = ECDsa.Create(ECCurve.NamedCurves.nistP256);
        byte[] message = Encoding.UTF8.GetBytes("{\"orderId\":42,\"amount\":99.95}");

        byte[] signature = signer.SignData(message, HashAlgorithmName.SHA256); // private key

        // The verifier only needs the public key (e.g. from a JWKS or certificate).
        string publicPem = signer.ExportSubjectPublicKeyInfoPem();
        using var verifier = ECDsa.Create();
        verifier.ImportFromPem(publicPem);
        bool ok = verifier.VerifyData(message, signature, HashAlgorithmName.SHA256);
        Console.WriteLine(ok); // True; change one byte of message and it is False
    }
}

public sealed record Envelope(byte[] WrappedKey, byte[] Nonce, byte[] Ciphertext, byte[] Tag);

public static class HybridEncryption
{
    public static Envelope Seal(RSA recipientPublic, byte[] data)
    {
        byte[] dek = RandomNumberGenerator.GetBytes(32);
        byte[] nonce = RandomNumberGenerator.GetBytes(12);
        byte[] ct = new byte[data.Length], tag = new byte[16];

        using (var aes = new AesGcm(dek, 16))
            aes.Encrypt(nonce, data, ct, tag);

        // RSA only wraps the 32-byte key: OAEP, never PKCS#1 v1.5 for encryption.
        byte[] wrapped = recipientPublic.Encrypt(dek, RSAEncryptionPadding.OaepSHA256);
        CryptographicOperations.ZeroMemory(dek);
        return new Envelope(wrapped, nonce, ct, tag);
    }

    public static byte[] Open(RSA recipientPrivate, Envelope e)
    {
        byte[] dek = recipientPrivate.Decrypt(e.WrappedKey, RSAEncryptionPadding.OaepSHA256);
        byte[] plain = new byte[e.Ciphertext.Length];
        using var aes = new AesGcm(dek, 16);
        aes.Decrypt(e.Nonce, e.Ciphertext, e.Tag, plain);
        CryptographicOperations.ZeroMemory(dek);
        return plain;
    }
}

⚠ Common mistakes

  • Mistake: "Encrypting with the private key" to sign. Why it is wrong: signing is a different operation with different padding; the mental model leads to misuse of encryption APIs. Instead: use SignData/VerifyData.
  • Mistake: Using RSAEncryptionPadding.Pkcs1 for new encryption. Why it is wrong: it is vulnerable to padding-oracle attacks. Instead: RSAEncryptionPadding.OaepSHA256.
  • Mistake: Encrypting whole payloads with RSA. Why it is wrong: size limits (about 190 bytes at 2048-bit with OAEP-SHA256) and poor performance. Instead: hybrid encryption with AES-GCM.
  • Mistake: Generating 1024-bit RSA keys or using legacy defaults. Why it is wrong: below current minimums in the ISM and NIST guidance. Instead: 2048 minimum, 3072 for long-lived keys, or P-256.
  • Mistake: Storing private keys as PEM files in the repo or container image. Why it is wrong: anyone with the image can sign as you. Instead: Key Vault keys (HSM-backed for high value) with sign/unwrap operations.
  • Mistake: Sharing one HMAC secret with many external verifiers. Why it is wrong: any of them can forge messages. Instead: sign with a private key and publish the public key.
  • Mistake: Treating a successful verify as authorisation. Why it is wrong: a valid signature only proves who signed it, not that the signer is allowed to do the action. Instead: check the key id against a trusted set and apply authorisation.

🏛 Senior insight: trade-offs

The design question is rarely RSA vs ECDSA; it is who needs to hold what. If only you produce and verify, HMAC or AES is simpler and faster. If many parties verify but only you produce, use signatures and publish public keys with key ids. If parties you don't control must send you secrets, use public-key encryption or ECDH. Then make the private key non-exportable in Key Vault so the application never sees it.

Operationally, asymmetric keys are a lifecycle problem: give every key an id, an expiry and a rotation policy (Key Vault supports automatic key rotation), publish the next public key before you start signing with it, and keep the previous one verifiable until everything signed with it has expired. Inventory where RSA and ECC are used now, because the post-quantum migration (ASD recommends ceasing traditional asymmetric cryptography by the end of 2030) starts with knowing what you have.

Need Choice Cost When not
Many verifiers, one issuer (JWTs, webhooks to many customers) ES256 or RS256/PS256 with JWKS Key publication and rotation Single internal verifier: HMAC is enough
Receive secrets from third parties RSA-OAEP / ECDH + AES-GCM Key distribution Both parties already share a channel like TLS
Long-term archives RSA-3072+/P-384 now, plan for ML-KEM/ML-DSA Bigger keys and signatures Short-lived data
High-value private keys Key Vault Managed HSM Cost, latency, throttling High-volume, low-value signing

Measure signing throughput if you issue tokens at scale: RSA private-key operations are expensive, and remote Key Vault signing adds a network round trip and throttling limits.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions RS256 or ES256 for JWTs. Why: Checks JWT signing algorithms and the validation parameters that matter.
    How to answer

    A JWT is three base64url parts, header.payload.signature. The header says which algorithm and key (alg, kid) signed it; the payload holds claims (iss, aud, sub, exp, scopes); the signature proves nobody changed them. It is signed, not encrypted, so anyone holding it can read it: no personal or secret data.

    • RS256/ES256: the identity provider signs with a private key and APIs verify with the public key from its JWKS endpoint. HS256 uses one shared secret, so every verifier could also forge tokens.
    • In ASP.NET Core, AddJwtBearer with Authority and Audience validates issuer, audience, lifetime and signature (with a 5-minute ClockSkew).

    The trade-off: validation is local and fast, but a stolen token is valid until exp, so keep access tokens short-lived.

  2. When: Candidate says TLS uses asymmetric crypto for the handshake. Why: Checks understanding of the TLS 1.3 handshake and certificate validation.
    How to answer

    HTTPS is HTTP inside TLS. TLS gives confidentiality (encryption), integrity (tamper detection) and server authentication (certificates).

    TLS 1.3 handshake (one round trip): the client sends supported ciphers, a key share, SNI (hostname) and ALPN (h2); the server replies with its key share, certificate chain and a signature proving it owns the private key. Both derive session keys via ECDHE (forward secrecy).

    The client validates: chain to a trusted root, not expired, hostname matches the SAN, and optionally revocation.

    For "remote certificate is invalid": read the SslPolicyErrors / chain status, inspect with openssl s_client -showcerts, then fix the real cause (expired cert, missing intermediate, wrong hostname, or a private/corporate root CA not trusted in the container). Never return true from ServerCertificateCustomValidationCallback in production.

  3. When: Candidate explains hybrid encryption with an AES key. Why: Checks correct use of AES-GCM nonces, tags and key storage.
    How to answer

    AesGcm is .NET's authenticated encryption API: AES in Galois/Counter Mode gives confidentiality and integrity in one step. You need a 256-bit key, a 12-byte nonce that is unique per encryption under that key, and you get a 16-byte tag; decryption throws AuthenticationTagMismatchException if anything was changed. Store keyId | nonce | ciphertext | tag together.

    The one rule you can't break: never reuse a nonce with the same key. GCM is a stream cipher underneath, so reuse leaks the XOR of the two plaintexts and exposes the authentication key, letting an attacker forge messages. Use random nonces and rotate keys well before about 2^32 messages. Compared with AES-CBC, GCM has no padding oracle and no separate MAC to get wrong. For most app needs, ASP.NET Core Data Protection or SQL Always Encrypted wraps this for you.

🛠 Real-world problems: how you handle them

Partner integration encrypting files with RSA PKCS#1 v1.5
Situation
A [superannuation fund] received member files from [a payroll partner] encrypted with RSA PKCS#1 v1.5 directly, chunked into 245-byte blocks; [about 50,000] files a month, each holding personal information.
Signals
A security review flagged the padding mode; decryption errors returned distinct HTTP error messages for bad padding vs bad data; processing a large file took [minutes] of CPU.
Investigation
Reviewed the partner's specification and our decryption endpoint; reproduced the different error responses with crafted input in a test environment; profiled decryption with dotnet-trace and saw RSA private-key operations dominating CPU.
Resolution
Immediately unified all decryption failures into one generic error and logged details server-side only. Agreed a new format with the partner: AES-256-GCM per file with the key wrapped by RSA-OAEP-SHA256 using our Key Vault key, with a transition window accepting both.
Prevention
An integration standard document listing approved algorithms; contract tests for the file format; Key Vault key with expiry and rotation policy; alerts on decryption failure rates.

How to tell it (STAR)

**S:** At [company] a [payroll partner] sent us member files encrypted chunk by chunk with RSA PKCS#1 v1.5. **T:** I was asked to fix the security finding without breaking a monthly flow of [50,000] files. **A:** I closed the immediate padding-oracle risk by making all decryption errors identical, then designed a hybrid format: AES-GCM for the file and RSA-OAEP to wrap the key held in Key Vault. I wrote the spec and a reference .NET implementation for the partner and ran both formats in parallel for [a month]. **R:** The finding was closed, decryption CPU dropped [about 95%], and the partner cut over with [zero] failed files.

↩ Usually asked after

More in Cryptography

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me