首页 > 解决方案 > 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);

请帮忙。

标签: c#ssldotnet-httpclient

解决方案


尝试使用 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 证书也可以正常工作。


推荐阅读