c# - 使用 RestSharp 根据要求添加证书

标签 c# x509certificate restsharp

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

为了测试服务器,我使用 Postman . 所以我在 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# 中工作的东西

最佳答案

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

首先,我不得不停止使用证书的 .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/

相关文章:

C# - ToList() 和 ToArray() 的奇怪行为

java - 无法解析证书 : java. io.IOException:空输入 X509Certificate

c# - 如果 header 不存在,如何获取空值

c# - 机器身份验证方案 C#

python-3.x - Python AAD(Azure Active Directory)使用证书进行身份验证

c# - 使用 RestSharp 将 JSON 数组反序列化为 C# 结构

c# - Restsharp - 尝试序列化根节点上的 xmlns 属性时出错

c# - RestSharp 将 Json 对象序列化为 Post 参数

c# - File.WriteAllLines 静默失败

c# - 在 C# 中使用类型作为函数参数创建通用对象