Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RemoteCertificateValidationCallback with X509Certificate2

Tags:

c#

    X509Certificate2 certificate = new X509Certificate2();
    FileStream fileStream = File.Open(@"C:\openssl\bin\cert_key.p12", FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[fileStream.Length];

    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(certificate.ValidateRemoteCertificate);
    Client.ClientCredentials.ClientCertificate.Certificate = certificate;

The problem I have with the above code is that the RemoteCertificateValidationCallback only accepts the older X509Certificate not X509Certificate2 type as a parameter. I need X509Certificate2 because the third-party API that I send SOAP request to requires version 2.

like image 223
PositiveGuy Avatar asked Jan 28 '10 16:01

PositiveGuy


2 Answers

The X509Certificate2 class has a constructor that takes a X509Certificate as parameter. So you can do this:

RemoteCertificateValidationCallback callback = delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslError) {
    X509Certificate2 certv2 = new X509Certificate2(cert);
    // more code here that sends soap request
    return false;
};
like image 88
λ Jonas Gorauskas Avatar answered Sep 30 '22 18:09

λ Jonas Gorauskas


I don't see why that is a problem. X509Certificate2 inherits from X509Certificate and can therefore be casted to one.

EDIT:

Furthermore X509Certificate2 has a constructor that takes a filename so you don't need the FileStream. Also I don't see you using the buffer anywhere?

like image 45
Klaus Byskov Pedersen Avatar answered Sep 30 '22 18:09

Klaus Byskov Pedersen