Reputation: 2673
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;
}
Upvotes: 1
Views: 7736
Reputation: 480
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"));
Upvotes: 4
Reputation: 409
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"));
Upvotes: 0