gpt4 book ai didi

C# 使用 .pem 文件验证服务器证书

转载 作者:行者123 更新时间:2023-12-04 22:36:21 25 4
gpt4 key购买 nike

我发现向启用 SSL 的 API 发送 http 请求时出现问题。我得到的错误信息是 -

AuthenticationException: The remote certificate is invalid according to the validation procedure.

基于这个请求

using (HttpResponseMessage res = client.GetAsync("https://example.com").Result)
{
using (HttpContent content = res.Content)
{
string data = content.ReadAsStringAsync().Result;
if (data != null)
{
Console.WriteLine(data);
}
else
{
Console.WriteLine("Nothing returned");
}
}
}

我得到了一个 .pem 文件来验证发回的证书是否由我们的 CA 签名,但在弄清楚如何在 C# 中执行此操作时遇到了一些问题

在 python 中,我可以通过将 .pem 文件传递​​给验证参数来解决证书错误,例如

r = requests.post(url="https://example.com", headers=headers, verify='mypem.pem') 

Dotnet Core 3 的 HttpClient 中是否有等效的东西?

感谢您的帮助!

最佳答案

如果您出于某种原因无法将证书设置为受信任的,那么您可以绕过证书验证并自行验证服务器。不幸的是,它在 .NET 中就没那么优雅了,而且这可能不适用于所有平台。引用this answerbypass invalid SSL certificate in .net core对此进行更多讨论。

using (var httpClientHandler = new HttpClientHandler())
{
// Override server certificate validation.
httpClientHandler.ServerCertificateCustomValidationCallback = VerifyServerCertificate;
// ^ if this throws PlatformNotSupportedException (on iOS?), then you have to use
//httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
// ^ docs: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.dangerousacceptanyservercertificatevalidator?view=netcore-3.0

using (var client = new HttpClient(httpClientHandler))
{
// Make your request...
}
}

我认为回调的这个实现可以满足您的需求,“固定”CA。来自 this answerForce HttpClient to trust single Certificate ,以及我的更多评论。 编辑:该答案的状态检查无效,但根据 this answer由 Jeremy Farmer 链接,以下方法应该:

    static bool VerifyServerCertificate(HttpRequestMessage sender, X509Certificate2 certificate,
X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
try
{
// Possibly required for iOS? :
//if (chain.ChainElements.Count == 0) chain.Build(certificate);
// https://forums.xamarin.com/discussion/180066/httpclienthandler-servercertificatecustomvalidationcallback-receives-empty-certchain
// ^ Sorry that thread is such a mess! But please check it.

// Without having your PEM I am not sure if this approach to loading the cert works, but there are other ways. From the doc:
// "This constructor creates a new X509Certificate2 object using a certificate file name. It supports binary (DER) encoding or Base64 encoding."
X509Certificate2 ca = new X509Certificate2("mypem.pem");

X509Chain chain2 = new X509Chain();
chain2.ChainPolicy.ExtraStore.Add(ca);

// "tell the X509Chain class that I do trust this root certs and it should check just the certs in the chain and nothing else"
chain2.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;

// This setup does not have revocation information
chain2.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;

// Build the chain and verify
var isValid = chain2.Build(certificate);
var chainRoot = chain2.ChainElements[chain2.ChainElements.Count - 1].Certificate;
isValid = isValid && chainRoot.RawData.SequenceEqual(ca.RawData);

Debug.Assert(isValid == true);

return isValid;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}

return false;
}

抱歉,我目前无法对此进行测试,但希望它能有所帮助。

关于C# 使用 .pem 文件验证服务器证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63348780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com