2015-12-06 71 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();" 

,瞧!!!