使用RestSharp根据请求添加证书

时间:2018-03-02 12:30:09

标签: c# x509certificate restsharp

我正在尝试与服务器通信。此服务器向我发送证书和私钥,以便成功执行我的请求。

要测试服务器,我使用Postman。 所以我填写邮递员的证书设置,我的请求工作正常

Postman settings for certificates

现在我想在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#中工作的

1 个答案:

答案 0 :(得分:2)

好的,我得到了解决方案。

首先,我不得不停止使用.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);