c# - HttpClient - 收到的消息是意外的或格式错误
问题描述
我正在尝试连接到需要配置两种方式 SSL 的 API。我有我在邮递员中配置的证书和私钥,如下图所示。
这在 Postman 中运行良好,但是当我尝试使用 HttpClient 在 C# 中实现它时 SSL 失败。我得到的错误是“收到的消息意外或格式错误。”。我相信这与不正确的配置有关。
我参考了这篇 StackOverflow 帖子来实现我的代码:Associate a private key with the X509Certificate2 class in .net
以下是我尝试过的:
byte[] publicCertificateBytes = File.ReadAllBytes("<Public Certificate>");
var publicCertificate = new X509Certificate2(publicCertificateBytes);
byte[] privateKey = Convert.FromBase64String(File.ReadAllText("<private key file>").Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", ""));
using (var rsa = RSA.Create())
{
rsa.ImportPkcs8PrivateKey(privateKey, out _);
publicCertificate = publicCertificate.CopyWithPrivateKey(rsa);
publicCertificate = new X509Certificate2(publicCertificate.Export(X509ContentType.Pkcs12));
}
var httpService = new GenericUtilityManager().ResolveUtility<IHttpService>();
var handler = new HttpClientHandler();
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(publicCertificate);
handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
httpService.InitializeHttpClientHandler(handler);
请帮忙。
解决方案
尝试使用 CreateFromPem 静态函数加载证书,此方法返回带有私钥的新证书。
var certificateCrt = File.ReadAllText("<Public Certificate>");
var privateKey = File.ReadAllText("<private key file>");
using var certificate = X509Certificate2.CreateFromPem(certificateCrt, privateKey);
如果这不起作用,请尝试使用 OpenSSL 创建 .pfx 证书:
openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt
当我需要在 Windows 操作系统上使用证书时,我遇到了这个问题,为了工作,我必须创建一个 .pfx 证书,但在 Mac 和 Linux 等其他操作系统上,没有 .pfx 证书也可以正常工作。
推荐阅读
- reactjs - 如何拥有更简洁的代码(当您的文本是其他语言而不是英语时)
- python - 如何根据熊猫数据框中的频率创建词云
- android - 如何在其上创建预定的网站解析和通知?
- javascript - 是否可以自动完成分为不同步骤的表单的所有字段?
- java - php返回的Json对象为空
- javascript - 如何从传递的表中获取行数?
- python - 深度学习、信号处理和特征工程
- python - python win32.client 从其自己的发件箱文件夹中的辅助 Outlook 帐户发送电子邮件
- php - 如何从具有许多不同关系的表中删除并删除项目和所有相关项?
- cmake - 使用 cmake 编译 Magick++ 代码的链接器错误