HttpWebRequest客户端身份验证

时间:2013-01-09 16:28:39

标签: c# httpwebrequest ssl-certificate

我需要将一些xmls发布到具有客户端证书身份验证的https站点,但无法成功完成。

我有以下提供商提供的2.pem文件:(我无法发送所有数据如此切割)

cert.pem:

-----开始证书----- MIIC0DCCAjmgAwIBAgIKAd8CIHEBAwIEpjANBgkqhkiG9w0BAQUFADCBmTELMAkG

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

key.pem:

-----开始RSA私钥----- MIICWwIBAAKBgQC + HN6jHJD1zoGLHYj1ycvg1yajll5zb3gExoWv7k + RbXLGuDEX

----- END RSA私钥-----

我试图做的是

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 个答案:

答案 0 :(得分:2)

您需要将私钥和pem证书转换为#pkcs12格式:

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

在此之后,您可以在C#代码中指定此p12文件:

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

答案 1 :(得分:1)

您需要将证书(公钥)发送到服务器,方法是将其添加到请求中。据我所知,服务器使用私钥来验证请求。

尝试简单地加载公钥文件,如果不能正常工作,则需要将其转换为ASN.1 DER格式。

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