Let's say I have three certificates (in Base64 format)
Root
|
--- CA
|
--- Cert (client/signing/whatever)
How can I validate the certs and certificate path/chain in C#?
(All those three certs may not be in my computer cert store)
Edit: BouncyCastle has the function to verify. But I'm trying not to use any third-party library.
byte[] b1 = Convert.FromBase64String(x509Str1);
byte[] b2 = Convert.FromBase64String(x509Str2);
X509Certificate cer1 =
new X509CertificateParser().ReadCertificate(b1);
X509Certificate cer2 =
new X509CertificateParser().ReadCertificate(b2);
cer1.Verify(cer2.GetPublicKey());
If the cer1 is not signed by cert2 (CA or root), there will be exception. This is exactly what I want.
Best Answer
The
X509Chain
class was designed to do this, you can even customize how it performs the chain building process.The
X509Chain
will contain additional information about the validation failure afterBuild() == false
if you need it.Edit: This will merely ensure that your CA's are valid. If you want to ensure that the chain is identical you can check the thumbprints manually. You can use the following method to ensure that the certification chain is correct, it expects the chain in the order:
..., INTERMEDIATE2, INTERMEDIATE1 (Signer of INTERMEDIATE2), CA (Signer of INTERMEDIATE1)
I am unable to test this because I don't have a full CA chain with me, so it would be best to debug and step through the code.