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);
}
如何在另一端檢查證書?證書是否有私鑰?爲什麼使用'X509Certificate'而不是'X509Certificate2'?另外,您還應該使用'X509Certificate2Collection'而不是'X509CertificateCollection'。當你使用'X509Certificate2'時,'HasPrivateKey'屬性的值是多少? –
此外,您的代碼導致內存泄漏,因爲沒有代碼關閉證書存儲。 https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.close(v=vs.110).aspx將'finally'塊添加到第一個try/catch子句。 – Crypt32
HasPrivateKey是真實的。它應該還是不應該包含PrivateKey? – Maverik