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.
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.
"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)orECDsa.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."
| 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) |
| Symmetric strength | RSA | Elliptic curve |
|---|---|---|
| 112-bit | 2048 | P-224 |
| 128-bit | 3072 | P-256 |
| 192-bit | 7680 | P-384 |
| 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) |
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.
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
Red flags
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.
"Textbook" RSA is deterministic and malleable: E(a) * E(b) = E(a*b). Padding adds randomness and structure.
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.
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.
RSA.SignData (3072) vs ECDsa.SignData (P-256) vs verify for both with BenchmarkDotNet.CryptographyClient.WrapKey on an AES key.MLDsa.IsSupported on your machine and in a Linux container with OpenSSL 3.5.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;
}
}
SignData/VerifyData.RSAEncryptionPadding.Pkcs1 for new encryption. Why it is wrong: it is vulnerable to padding-oracle attacks. Instead: RSAEncryptionPadding.OaepSHA256.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.
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.
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.
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.
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.
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.
Last updated 23 Nov 2026.