kexu
kexu

Reputation: 306

X509Chain.Build(...) System.InvalidCastException from X509Certificate to X509Certificate2

I am trying to verify a certificate chain using a custom certificate authority. Why is an exception thrown on the last line of this code?

using System.Security.Cryptography.X509Certificates;

string BaseCertsDir = "Certificates\\";

X509Certificate serverCrt = new(BaseCertsDir + "Server\\Server.crt");
X509Certificate intermediateCert = new(BaseCertsDir + "IntermediateCA\\IntermediateCA.crt");
X509Certificate rootCert = new(BaseCertsDir + "RootCA\\RootCA.crt");

X509Chain chain = new();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Clear();
chain.ChainPolicy.CustomTrustStore.Add(rootCert);

chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;

chain.ChainPolicy.ExtraStore.Add(intermediateCert);

chain.Build(new X509Certificate2(serverCrt));

The exception:

Exception thrown: 'System.InvalidCastException' in System.Private.CoreLib.dll
An unhandled exception of type 'System.InvalidCastException' occurred in System.Private.CoreLib.dll
Unable to cast object of type 'System.Security.Cryptography.X509Certificates.X509Certificate' to type 'System.Security.Cryptography.X509Certificates.X509Certificate2'.

Upvotes: 0

Views: 529

Answers (1)

kexu
kexu

Reputation: 306

I was able to get the code working by converting rootCert and intermediateCert to X509Certificate2 before adding:

chain.ChainPolicy.CustomTrustStore.Add(new X509Certificate2(rootCert));
chain.ChainPolicy.ExtraStore.Add(new X509Certificate2(intermediateCert));

Upvotes: 1

Related Questions