gpt4 book ai didi

c# - 如何在 C# 中手动验证自签名证书?

转载 作者:太空宇宙 更新时间:2023-11-03 15:09:16 25 4
gpt4 key购买 nike

在过去的几周里,我一直在 Docker 容器中工作,我遇到了自签名证书导致问题的障碍,因为 Docker 容器无法识别证书颁发机构。

问题是我无法将自己的证书放在服务器配置上,因为我们在公司使用 Docker 的方式。

最佳答案

经过大量研究,我想出了一个解决方案,该解决方案基于构建链和指纹验证来手动验证证书。

注意:您必须使用支持证书验证回调的库,以便您可以编写自己的委托(delegate)方法。下面是我的实现。

public static bool ManualSslVerification(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
try
{
//Testing to see if the Certificate and Chain build properly, aka no forgery.
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.Build(new X509Certificate2(certificate));

//Looking to see if there are no errors in the build that we don’t like
foreach (X509ChainStatus status in chain.ChainStatus)
{
if (status.Status == X509ChainStatusFlags.NoError || status.Status == X509ChainStatusFlags.UntrustedRoot)
{
//Acceptable Status, We want to know if it builds properly.
}
else
{
return false;
}
}

X509Certificate2 trustedRootCertificateAuthority = new X509Certificate2(ViewController.Properties.Resources.My_Infrastructure_Root_CA);

//Now that we have tested to see if the cert builds properly, we now will check if the thumbprint of the root ca matches our trusted one
if(chain.ChainElements[chain.ChainElements.Count – 1].Certificate.Thumbprint != trustedRootCertificateAuthority.Thumbprint)
{
return false;
}

//Once we have verified the thumbprint the last fun check we can do is to build the chain and then see if the remote cert builds properly with it
//Testing to see if the Certificate and Chain build properly, aka no forgery.
X509Chain trustedChain = new X509Chain();
trustedChain.ChainPolicy.ExtraStore.Add(trustedRootCertificateAuthority);
trustedChain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
trustedChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
trustedChain.Build(new X509Certificate2(certificate));

//Looking to see if there are no errors in the build that we don’t like
foreach (X509ChainStatus status in trustedChain.ChainStatus)
{
if(status.Status == X509ChainStatusFlags.NoError || status.Status == X509ChainStatusFlags.UntrustedRoot)
{
//Acceptable Status, We want to know if it builds properly.
}
else
{
return false;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}

return true;
}

关于c# - 如何在 C# 中手动验证自签名证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51137680/

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