我想使用网络服务(https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list)并根据文档(https://realtime-listings.webservices.zpg.co.uk/docs/latest/documentation.html)
我必须发送.crt和.pem文件进行身份验证。
我能够加载.crt文件,但对于.pem我收到错误Cannot find the requested object
。我尝试了不同的加载PEM文件的方法。
我已关注以下线程,但仍无法从.pem文件加载X509Certificate
。
我的代码如下
var webAddr = "https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.1/schemas/listing/list.json";
httpWebRequest.Method = "POST";
httpWebRequest.ClientCertificates.Add(X509Certificate.CreateFromCertFile(@"E:\ProcessZooplaData\zpg_realtime_listings_14810206-20261204.crt"));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
现在到这里一切都好了如果我尝试加载.pem文件然后我收到错误
var pem = System.IO.File.ReadAllText(@"E:\\ProcessZooplaData\\private.pem");
byte[] certBuffer = GetBytesFromPEM(pem, "RSA PRIVATE KEY");
var certificate = new X509Certificate(certBuffer);
httpWebRequest.ClientCertificates.Add(certificate);
byte[] GetBytesFromPEM(string pemString, string section)
{
var header = String.Format("-----BEGIN {0}-----", section);
var footer = String.Format("-----END {0}-----", section);
var start = pemString.IndexOf(header, StringComparison.Ordinal);
if (start < 0)
return null;
start += header.Length;
var end = pemString.IndexOf(footer, start, StringComparison.Ordinal) - start;
if (end < 0)
return null;
return Convert.FromBase64String(pemString.Substring(start, end));
}
我在Cannot find the requested object
收到错误。
其余代码如下
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"branch_reference\":\"test\"}";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
//return result;
}
我尝试过以下线程供参考 how to get private key from PEM file?
答案 0 :(得分:0)
如果您的证书已经加载到您的证书商店,那么您可以执行以下操作:
var requestHandler = new WebRequestHandler();
var store = new X509Store("My", StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, certificateName, true);
if (certificates.Count > 0)
requestHandler.ClientCertificates.Add(certificates[0]);
else
throw new Exception(string.Format("Can't find certificate {0}", certificateName));
using (var client = new HttpClient(requestHandler))
{
do work!
}
应该将商店中的证书添加到连接中。
然后,您需要在证书中打开证书存储区(运行mmc,将证书添加到本地计算机商店的控制台),浏览到您的证书,右键单击它并选择所有任务&gt;管理私钥并授予您的应用程序将在“读取”访问证书私钥的情况下运行的用户帐户,您无需打开任何文件即可执行此操作。
当然,如果您在无法访问证书的共享托管环境中执行此操作,或者无法将其安装到证书库中,则这是一个不同的问题。