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

📚 Interview question

How do digital signatures and X.509 certificates work together? Explain what a certificate contains, how a chain of trust is validated, how you would sign and verify a token or document in .NET, and why .NET 9 introduced X509CertificateLoader to replace the X509Certificate2 constructors.

Covers digital signatures and X.509 in .NET: certificate fields, chain building and revocation, signing documents and tokens with certificate keys, X509Chain validation, and the move to X509CertificateLoader (SYSLIB0057) in .NET 9 and later.

Mid-Level Theory Intermediate certificates cryptography digital-signatures dotnet security x509

🎯 Key points

  • A signature = sign(cryptographic hash of the data, e.g. SHA-256) with a private key; collision resistance of the hash is what makes signing the digest safe
  • A certificate binds a public key to a subject, signed by an issuing CA; fields: subject, SAN, issuer, validity, serial
  • Key usage and EKU constrain what the key may do: serverAuth, clientAuth, codeSigning, emailProtection, document signing
  • Chain validation: leaf -> intermediates -> trusted root, plus validity dates, EKU, revocation (CRL/OCSP); the hostname is checked separately
  • X509Chain with ChainPolicy (CustomRootTrust, RevocationMode) for scoped custom trust
  • X509CertificateLoader (.NET 9+) makes the expected format explicit; the content-sniffing constructors are obsolete (SYSLIB0057)
  • Never disable validation (a callback returning true)
  • Lifecycle: non-exportable keys, automated renewal, expiry monitoring, overlapping rotation

⏱ 30-second answer

A digital signature is a hash of the data transformed with a private key; anyone with the matching public key can verify the data is unchanged and came from the key holder. An X.509 certificate answers "whose public key is this?": it binds a public key to a subject (and SAN names), with validity dates and key usages, and is itself signed by a CA. Verifying means building a chain from the leaf through intermediates to a trusted root, checking dates, EKU, name and revocation.

In .NET you sign with cert.GetECDsaPrivateKey() or GetRSAPrivateKey() and validate with X509Chain. Since .NET 9, load certificates with X509CertificateLoader (LoadCertificate, LoadPkcs12): the old X509Certificate2 constructors are obsolete (SYSLIB0057) because they guessed the format from content. The trade-off: PKI gives verifiable identity at the cost of lifecycle management.

🗣 Full answer (senior)

How I would answer this in an interview

"A signature gives integrity and authenticity: I hash the data and sign the hash with my private key, and the verifier checks it with my public key. The problem is trust in the public key itself, and that's what X.509 solves. A certificate says 'this public key belongs to api.contoso.com.au', with a validity period, key usage and extended key usage like server authentication or code signing, and it's signed by a certificate authority. The CA's certificate is signed by another, up to a root the operating system or my configuration already trusts.

Validation is more than checking a signature. X509Chain.Build walks leaf to intermediate to root, checks each signature, the dates, the EKU and the revocation status through CRL or OCSP, and the caller still has to check the name. For internal PKI I set ChainPolicy.TrustMode = CustomRootTrust and add our root to CustomTrustStore instead of installing it machine-wide.

In code, signing a document or a token with a certificate is cert.GetECDsaPrivateKey().SignData(...), and verification uses the public key from the certificate after the chain is validated. Since .NET 9, I load certificates with X509CertificateLoader.LoadCertificateFromFile or LoadPkcs12FromFile. The old constructors sniffed the content and would happily load PFX, PEM, DER or even PKCS#7, which meant an API expecting a public certificate could end up parsing a PFX with a private key and touching the key store. The loader makes the format explicit and applies PKCS#12 limits.

The mistake I see is a ServerCertificateCustomValidationCallback that returns true to 'fix' a dev error, which then ships to production and disables TLS authentication completely."


What's in a certificate

Field Meaning
Subject / SAN Who it identifies; browsers and .NET match the hostname against the SAN
Issuer The CA that signed it
Validity NotBefore / NotAfter
Public key RSA or EC key
Key usage / EKU digitalSignature, serverAuth, clientAuth, codeSigning
Serial, extensions Revocation pointers (CRL distribution point, OCSP via AIA)
Signature The CA's signature over all of the above

Chain validation checks

Check Failure in .NET (X509ChainStatusFlags)
Signature chain to a trusted root UntrustedRoot, PartialChain
Dates NotTimeValid
Revocation Revoked, RevocationStatusUnknown
Usage NotValidForUsage
Name Not checked by X509Chain; TLS stack or your code must check it

Loader APIs (.NET 9+)

Old New
new X509Certificate2(path) (PEM/DER) X509CertificateLoader.LoadCertificateFromFile(path)
new X509Certificate2(pfxPath, password) X509CertificateLoader.LoadPkcs12FromFile(pfxPath, password)
new X509Certificate2(bytes) X509CertificateLoader.LoadCertificate(bytes)
PEM with key X509Certificate2.CreateFromPemFile(certPath, keyPath)

Production example

We signed [PDF statements] for [a lender] with an HSM-backed certificate in Key Vault: the app hashes each document and calls Key Vault Sign, so the private key never leaves the HSM. [About 40,000] statements a night signed in [under 15 minutes], with Key Vault throttling as the limit, not CPU.

🔍 What the interviewer is checking

Checks understanding of how signatures, certificates and chain validation fit together, and current .NET certificate APIs.

Green flags

  • Explains that a certificate binds identity to a public key and is CA-signed
  • Lists chain checks including EKU and revocation, and notes name checking
  • Knows X509CertificateLoader and why the constructors were obsoleted
  • Keeps private keys non-exportable

Red flags

  • "Just accept all certificates" in any environment
  • Confuses the certificate with the private key
  • No idea how trust is established

📚 Learn in depth

1. Signature flow

Signer:   digest = SHA-256(document)
          sig    = Sign(privateKey, digest)            -> ship (document, sig, certificate)
Verifier: validate certificate chain -> trusted? usage ok? not revoked?
          Verify(cert.PublicKey, SHA-256(document), sig)

The certificate is what turns "a valid signature from some key" into "a valid signature from Contoso Pty Ltd".

2. Chain building

[ Root CA ]  self-signed, in the trust store (or CustomTrustStore)
     | signs
[ Intermediate CA ]  sent by the server or fetched via AIA
     | signs
[ Leaf: api.contoso.com.au ]  SAN, EKU serverAuth, 200-day validity

Servers must send intermediates; missing intermediates are the classic "works in the browser, fails in a Linux container" bug, because browsers fetch or cache them while OpenSSL-based clients may not.

3. Revocation

CRLs are lists published by the CA; OCSP is an online query; OCSP stapling lets the server include a signed response. RevocationMode.Online costs network calls and can hang when offline, NoCheck is a conscious risk. Shorter certificate lifetimes (public TLS maximum 200 days since March 2026, falling to 47 days by 2029 under CA/Browser Forum ballot SC-081) reduce reliance on revocation.

4. Why X509CertificateLoader

The X509Certificate2(byte[]) constructor detected the format from content. That allowed surprising behaviour: a PFX loaded where a public cert was expected, private keys written to disk-backed key stores, and expensive or malicious PKCS#12 files (huge iteration counts) parsed by code that never meant to accept them. The loader is explicit per format and enforces Pkcs12LoaderLimits.

5. Signing tokens and documents

  • JWTs: X509SigningCredentials or ECDsaSecurityKey with the cert key; publish the cert/key in JWKS with a kid or x5t.
  • XML: SignedXml (XMLDSig) for SAML and legacy integrations.
  • Raw: SignedCms for CMS/PKCS#7 detached signatures.
  • Remote: Key Vault CryptographyClient.SignAsync with a digest.

Try it yourself

  1. Create a self-signed CA and a leaf with CertificateRequest, then validate the leaf with X509Chain and CustomRootTrust.
  2. Remove the intermediate and observe PartialChain.
  3. Replace new X509Certificate2(...) calls in a project and fix SYSLIB0057 warnings.
  4. Sign a file with a certificate's ECDSA key and verify it with only the .cer public certificate.
  5. Inspect a public site's chain with openssl s_client -showcerts.

💻 Code

Loading certificates with X509CertificateLoader, validating a chain against a private root, and signing and verifying a document.

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace Documents.Signing;

public sealed class DocumentSigner(X509Certificate2 signingCert)
{
    public byte[] Sign(ReadOnlySpan<byte> document)
    {
        using ECDsa key = signingCert.GetECDsaPrivateKey()
            ?? throw new InvalidOperationException("Certificate has no ECDSA private key.");
        return key.SignData(document, HashAlgorithmName.SHA256);
    }
}

public sealed class DocumentVerifier(X509Certificate2 trustedRoot)
{
    public bool Verify(byte[] document, byte[] signature, X509Certificate2 signerCert)
    {
        using var chain = new X509Chain();
        chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; // only our PKI
        chain.ChainPolicy.CustomTrustStore.Add(trustedRoot);
        chain.ChainPolicy.RevocationMode = X509RevocationMode.Online;
        chain.ChainPolicy.ApplicationPolicy.Add(new Oid("1.3.6.1.5.5.7.3.3")); // EKU: code/document signing

        if (!chain.Build(signerCert)) return false;  // inspect chain.ChainStatus for diagnostics

        using ECDsa? publicKey = signerCert.GetECDsaPublicKey();
        return publicKey is not null && publicKey.VerifyData(document, signature, HashAlgorithmName.SHA256);
    }
}

public static class CertificateLoading
{
    // .NET 9+: explicit formats instead of the obsolete constructors (SYSLIB0057).
    public static X509Certificate2 LoadRoot(string path) =>
        X509CertificateLoader.LoadCertificateFromFile(path);                 // .cer / .crt (DER or PEM)

    public static X509Certificate2 LoadSigner(string pfxPath, string password) =>
        X509CertificateLoader.LoadPkcs12FromFile(pfxPath, password,
            X509KeyStorageFlags.EphemeralKeySet);                           // avoid persisting the key
}

⚠ Common mistakes

  • Mistake: ServerCertificateCustomValidationCallback = (_, _, _, _) => true. Why it is wrong: it removes the only thing proving who you are talking to, so anyone on the path can intercept, read and alter traffic, including credentials and tokens, and the client will never notice. Instead: fix the chain, or trust a specific private root with CustomRootTrust.
  • Mistake: Verifying a signature with the public key from an unvalidated certificate. Why it is wrong: anyone can create a self-signed certificate with your name. Instead: build and validate the chain first, including EKU.
  • Mistake: Installing an internal root CA machine-wide in containers. Why it is wrong: it widens trust for every outbound call. Instead: scoped CustomTrustStore in the handler that needs it.
  • Mistake: Continuing to use new X509Certificate2(bytes) in .NET 9+. Why it is wrong: format sniffing may parse unexpected PKCS#12 content and the API is obsolete. Instead: X509CertificateLoader.
  • Mistake: Loading PFX files with default flags on Windows servers. Why it is wrong: private keys get persisted to the machine key store and accumulate. Instead: EphemeralKeySet or keys in Key Vault.
  • Mistake: Not serving intermediate certificates. Why it is wrong: clients that don't fetch AIA get PartialChain errors. Instead: deploy the full chain.
  • Mistake: Renewing certificates by hand from a calendar reminder. Why it is wrong: with public TLS certificates limited to 200 days and heading to 47, manual renewal will eventually be missed and cause an outage. Instead: automated renewal (ACME, Key Vault auto-renew, App Service managed certificates) plus expiry alerts.
  • Mistake: Disabling revocation checks silently. Why it is wrong: a compromised certificate stays trusted. Instead: decide explicitly and document it; prefer short-lived certificates.

🏛 Senior insight: trade-offs

Certificates are an identity system with a lifecycle, and most incidents are lifecycle failures: expiry, missing intermediates, a rotated root nobody distributed. So the senior concerns are where the private key lives (non-exportable in Key Vault or an HSM), how renewal is automated, and how verifiers learn the new key (JWKS with key ids, overlapping validity).

Option When it fits Cost When not
Public CA certificate Internet-facing TLS Automated renewal needed (200-day max now) Internal service identity
Private CA (AD CS, Key Vault + CA integration) Internal mTLS, document signing Running a PKI Public browser trust
Raw key pair with JWKS Token signing Key publication When verifiers expect certificates
Key Vault HSM signing High-value signatures Latency, throttling Very high-throughput signing

Measure: days to expiry for every certificate, chain validation failures by status flag, and signing latency if keys are remote.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions TLS certificate validation errors. Why: Checks the TLS 1.3 handshake and safe fixes for remote certificate errors.
    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.

  2. When: Candidate mentions RSA or ECDSA keys inside certificates. Why: Checks encrypt vs sign, padding and key sizes.
    How to 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.

🛠 Real-world problems: how you handle them

Partner API calls fail in Linux containers after a certificate renewal
Situation
A [claims processing service] on AKS called [an insurer's partner API] over mTLS. After the partner renewed its server certificate, [every call from the Linux pods] failed while the same code worked on developer Windows machines.
Signals
`HttpRequestException: The SSL connection could not be established`, inner `AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: PartialChain`; error rate 100% on that dependency in Application Insights.
Investigation
Ran `openssl s_client -connect partner:443 -showcerts` from a debug pod and saw only the leaf certificate being sent; logged `chain.ChainStatus` in a temporary validation callback that still returned the default result; confirmed Windows was fetching the intermediate via AIA while the Linux image could not reach the AIA URL through the egress firewall.
Resolution
Short term: added the partner's intermediate to a `CustomTrustStore` for that named HttpClient only, without disabling validation. Long term: the partner fixed their server to send the full chain, and we removed the workaround.
Prevention
A synthetic test calling each partner endpoint from a Linux container in staging; a certificate-expiry and chain-check probe; a rule in code review that rejects validation callbacks returning `true`.

How to tell it (STAR)

**S:** At [company] our [claims service] stopped reaching [a partner's API] the morning after they renewed their certificate. **T:** I needed to restore the integration quickly without weakening TLS. **A:** I reproduced the error from a debug pod with `openssl s_client`, saw the partner was sending only the leaf, and confirmed Windows hid the problem by fetching the intermediate through AIA. I scoped the intermediate into a custom trust store on that one named client, kept full validation, and raised a ticket with the partner. **R:** Service was restored in [about 90 minutes], the partner fixed their chain within [a week], and our new Linux-based synthetic check has since caught [two] similar partner issues before users did.

↩ Usually asked after

More in Cryptography

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me