Boaz
Boaz

Reputation: 26109

How to use a PKCS#12 certificate file in a .NET WebRequest?

I have been issued a PKCS#12 certificate to be used for accessing a simple xml-based web service. When I load the PKCS#12 file into Windows (Vista), I can access the service using my browser.

Trying to access the service through an application, without loading the PKCS#12 into the OS Certificate collections , I have written the following code:

// The certificate i'm using can not be authenticated as it is a development one. 
// For now, just ignore it.
static bool myRemoteCertificateValidationCallback(
         Object sender,
         X509Certificate certificate,
         X509Chain chain,
         SslPolicyErrors sslPolicyErrors
)
{ return true; }

static void Main(string[] args)
{
    ServicePointManager.ServerCertificateValidationCallback = myRemoteCertificateValidationCallback;
    X509Certificate Cert = new X509Certificate(@"certificatefile.p12","medialab");
    HttpWebRequest Req = (HttpWebRequest)WebRequest.Create("https://ServiceURL");
    Req.ClientCertificates.Add(Cert);

    Stream S = Req.GetResponse().GetResponseStream();
    TextReader TR = new StreamReader(S);
    string Ret = TR.ReadToEnd();
    Console.Write(Ret);

}

Sadly this code fails and I get a System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel. I've noticed that when I do load the PKCS#12 file into Windows, the code suddenly works.

What do I need to do to make do with the file alone and avoid using the Windows Certificate store?

Thanks, Boaz

More info: Just applied SP1 to my Visual Studio and now I get a different exception: "A call to SSPI failed, see Inner exception" with the an Inner Exception -> "The message received was unexpected or badly formatted."

Upvotes: 1

Views: 4561

Answers (1)

Vladimir Kocjancic
Vladimir Kocjancic

Reputation: 1842

You have to have your certificate installed in Certificate Store. The easiest way is to use IE and import the certificate.

Upvotes: 2

Related Questions