![](/img/trans.png)
[英]How do I manually trust a self-signed certificate embedded in my application?
[英]How do I manually validate a self-signed certificate in C#?
在過去的幾周中,我一直在Docker容器中進行大量工作,並且遇到了自簽名證書導致問題的障礙,因為Docker容器無法識別證書頒發機構。
問題是我無法在服務器配置上放置自己的證書,因為我們在公司使用Docker的方式。
經過大量研究,我提出了一個解決方案,該解決方案基於構建鏈和驗證指紋的方式手動驗證證書。
注意:您必須使用支持證書驗證回調的庫,以便可以編寫自己的委托方法。 下面是我的實現。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.