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