2013-01-09 193 views
1

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

我从供应商提供的类似下面2的.pem文件:(我不能发送所以板缺的所有数据)

cert.pem:

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

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

key.pem:

-----乙EGIN 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; 
     } 

回答

1

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

试着简单地加载你的公钥文件,如果不工作,你需要将它转换为ASN.1 DER格式。

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

嗨,谢谢你的回答,但它不起作用。当我查看System.New跟踪日志时它尝试查找cert.pem私钥然后未能找到它,因此抛出异常 – Yucel

0

你需要你的私钥和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"));