2015-12-06 35 views
0

我想从我的证书存储中添加证书到HttpWebRequest对象。成功从商店获取证书并添加HttpWebRequest对象。但是,当发送请求时,在收件结束时证书不存在。不知道中间发生了什么。这是我的代码,它提取证书然后将其发送到接收服务器。该过程用于基于证书的身份验证(我试图用服务器验证自己)将证书添加到HttpWebRequestin C#

X509Store store = new X509Store("My", StoreLocation.LocalMachine); 
store.Open(OpenFlags.ReadOnly); 
// Look for the first certificate that is named Cartus-to-Microsoft. 
// Look in the local machine store. 
X509CertificateCollection col = (X509CertificateCollection)store.Certificates.Find(X509FindType.FindBySubjectName, certName, true); 
X509Certificate cert = null; 
try 
{ 
    if(col.Count>0) 
     cert = col[0]; 
} 
catch (Exception ex) 
{ 
    throw new Exception("Certificate not Found!"); 
} 

//HttpWebRequest req = null; 
HttpWebResponse rsp = null; 
string uri = "http://relofileservice.azurewebsites.net/api/datasync/reloPostService"; //"http://localhost:64952/api/datasync/reloPostService"; 
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri); 

//Add payload to request 
var data = Encoding.ASCII.GetBytes(json); 
req.Method = WebRequestMethods.Http.Post; 
req.ContentType = "application/x-www-forum-urlencoded"; 
req.ContentLength = data.Length; 
using (var stream = req.GetRequestStream()) 
{ 
    stream.Write(data, 0, data.Length); 
} 
//Build The request Header 
req.KeepAlive = false; 
req.UserAgent = "Cartus API Client"; 
req.ClientCertificates.Add(cert); 
System.Net.ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return true; }; 

Trace.TraceInformation("Certificate added to rquest"); 
try 
{ 
    //Send the request and receive response. 
    rsp = (HttpWebResponse)req.GetResponse(); 
} 
catch (Exception Ex) 
{ 
    Trace.TraceError("GetResponse Error Message: " + Ex.Message + ". GetResponse Error StackTrace: " + Ex.StackTrace); 
} 
+0

如何在另一端检查证书?证书是否有私钥?为什么使用'X509Certificate'而不是'X509Certificate2'?另外,您还应该使用'X509Certificate2Collection'而不是'X509CertificateCollection'。当你使用'X509Certificate2'时,'HasPrivateKey'属性的值是多少? –

+0

此外,您的代码导致内存泄漏,因为没有代码关闭证书存储。 https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.close(v=vs.110).aspx将'finally'块添加到第一个try/catch子句。 – Crypt32

+0

HasPrivateKey是真实的。它应该还是不应该包含PrivateKey? – Maverik

回答

0

找出来了。在发送证书之前需要完成两个步骤。没有任何博客或文件解释这两个步骤。有趣的是,在提出的解决方案中,重要的位常常被忽略。总之,这里是解决方案的最终花絮:

A]确保客户端证书是个人商店。 B]分配权限以读取试图从商店读取证书的用户帐户的私钥。

代码明智:

的X509Store店=新的X509Store(” 我的”,StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly);

  X509Certificate2Collection col = (X509Certificate2Collection)store.Certificates.Find(X509FindType.FindBySubjectName, certName, true); 
      X509Certificate2 cert = null; 
      try 
      { 
       if(col.Count>0) 
        cert = col[0]; 
      } 
      catch (Exception ex) 
      { 
       throw new Exception("Certificate not Found!"); 
      } 

      store.Close();" 

,瞧!!!