我正在尝试与服务器通信。该服务器向我发送证书和私钥,以便成功执行我的请求。
为了测试服务器,我使用 Postman . 所以我在 postman 中填写了证书设置,我的请求工作正常
现在我想在 C# 中做同样的事情。
为此我使用 RestSharp为了创建请求。
这是我的代码
var client = new RestClient(url);
byte[] certBuffer = UtilsService.GetBytesFromPEM(myCertificate, Models.Enum.PemStringType.Certificate);
byte[] keyBuffer = UtilsService.GetBytesFromPEM(encryptedPrivateKey, Models.Enum.PemStringType.RsaPrivateKey);
X509Certificate2 certificate = new X509Certificate2(certBuffer, secret);
client.ClientCertificates = new X509CertificateCollection() { certificate };
var request = new RestRequest(Method.POST);
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("myStuff", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
请求无效。我认为问题出在我如何在 RestSharp 中加载证书。
我正在寻找有关如何在 RestSharp 中正确设置证书的信息。
我正在使用 RestSharp,但我可以是任何可以在 C# 中工作的东西
最佳答案
好的,我找到了解决方案。
首先,我不得不停止使用证书的 .crt 和 .key。我必须得到一个 .pfx。这可以通过 openssl 命令 ( openssl documentation ) 完成
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt
创建证书后,像这样将其添加到请求中即可
var client = new RestClient(url);
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;
var certFile = Path.Combine(certificateFolder, "certificate.pfx");
X509Certificate2 certificate = new X509Certificate2(certFile, onboard.authentication.secret);
client.ClientCertificates = new X509CertificateCollection() { certificate };
client.Proxy = new WebProxy();
var restrequest = new RestRequest(Method.POST);
restrequest.AddHeader("Cache-Control", "no-cache");
restrequest.AddHeader("Accept", "application/json");
restrequest.AddHeader("Content-Type", "application/json");
restrequest.AddParameter("myStuff", ParameterType.RequestBody);
IRestResponse response = client.Execute(restrequest);
关于c# - 使用 RestSharp 根据要求添加证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069197/