1

I need to post some xmls to a https site with client certificate authentication, but couldn't do it successfully.

I have 2 .pem file supplied from provider like below: (I can't send all the data so cutted)

cert.pem:

-----BEGIN CERTIFICATE----- MIIC0DCCAjmgAwIBAgIKAd8CIHEBAwIEpjANBgkqhkiG9w0BAQUFADCBmTELMAkG

-----END CERTIFICATE-----

key.pem:

-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQC+HN6jHJD1zoGLHYj1ycvg1yajll5zb3gExoWv7k+RbXLGuDEX

-----END RSA PRIVATE KEY-----

What I was try to do is

private static string HttpRequest(string url, string data) { HttpWebRequest rq = (HttpWebRequest)WebRequest.Create(url); //string privateKey = File.ReadAllText("c:\\key.pem"); //privateKey = privateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", ""); //privateKey = privateKey.Replace("-----END RSA PRIVATE KEY-----", ""); //privateKey = privateKey.Replace("\n", ""); //Byte[] byteArr = Convert.FromBase64String(privateKey); //How do I use below .pem files here to authentica rq.ClientCertificates.Add(clientcert); rq.Method = "POST"; rq.Proxy = null; rq.ContentType = "application/www-form-urlencoded"; string dataToSend = data; byte[] byteArray = Encoding.UTF8.GetBytes(dataToSend); rq.ContentLength = byteArray.Length; string responseFromServer = null; try { Stream dataStream = rq.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse _WebResponse = rq.GetResponse(); dataStream = _WebResponse.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); responseFromServer = reader.ReadToEnd(); } catch (Exception ex) { } return responseFromServer; } 

2 Answers 2

4

You need to convert your private key and pem certificate into #pkcs12 form:

openssl pkcs12 -inkey private.key -in client_certificate.pem -export -out client_certificate.p12

After this, you can specify this p12 file in your C# code:

rq.ClientCertificates.Add(X509Certificate.CreateFromCertFile("c:\\client_certificate.p12"));

Sign up to request clarification or add additional context in comments.

Comments

0

You need sent you certificate (public key) to the server by adding it to the request. Server uses the private key to validate request as far as I know.

Try to simply load you public key file if not working you need to convert it to ASN.1 DER format.

rq.ClientCertificates.Add(X509Certificate.CreateFromCertFile("c:\\cert.pem")); 

1 Comment

Hi, thanks for your answer, but it doesn't work. When I looked to the System.New trace logs It tries to find the cert.pem private key then failed to find it, so throws exception

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.