如果您知道哪些证书可以作为证书检查的根和中间证书,您可以在X509Chain
对象的ChainPolicy.ExtraStore
集合中加载根和中间证书的公钥。
我的任务还包括编写一个Windows窗体应用程序来安装证书,但仅当它是依赖于我国政府已知的“国家根证书”发行的证书时。也只有一定数量的CA被允许颁发证书以验证连接到国家网络服务,因此我有一组有限的证书可以在链中,并且可能在目标计算机上缺失。我在应用程序的子目录“cert”中收集了所有CA和政府根证书的公钥:
在Visual Studio中,我将cert目录添加到解决方案中,并将该目录中的所有文件标记为嵌入式资源。这使我能够在我的C#库代码中枚举“受信任”的证书集合,以构建链以检查证书,即使未安装发行者证书。我为此编写了一个X509Chain的包装类:
private class X509TestChain : X509Chain, IDisposable
{
public X509TestChain(X509Certificate2 oCert)
: base(false)
{
try
{
ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
if (!Build(oCert) || (ChainElements.Count <= 1))
{
Trace.WriteLine("X509Chain.Build failed with installed certificates.");
Assembly asmExe = System.Reflection.Assembly.GetEntryAssembly();
if (asmExe != null)
{
string[] asResources = asmExe.GetManifestResourceNames();
foreach (string sResource in asResources)
{
if (sResource.IndexOf(".cert.") >= 0)
{
try
{
using (Stream str = asmExe.GetManifestResourceStream(sResource))
using (BinaryReader br = new BinaryReader(str))
{
byte[] abResCert = new byte[str.Length];
br.Read(abResCert, 0, abResCert.Length);
X509Certificate2 oResCert = new X509Certificate2(abResCert);
Trace.WriteLine("Adding extra certificate: " + oResCert.Subject);
ChainPolicy.ExtraStore.Add(oResCert);
}
}
catch (Exception ex)
{
Trace.Write(ex);
}
}
}
}
if (Build(oCert) && (ChainElements.Count > 1))
Trace.WriteLine("X509Chain.Build succeeded with extra certificates.");
else
Trace.WriteLine("X509Chain.Build still fails with extra certificates.");
}
}
catch (Exception ex)
{
Trace.Write(ex);
}
}
public void Dispose()
{
try
{
Trace.WriteLine(string.Format("Dispose: remove {0} extra certificates.", ChainPolicy.ExtraStore.Count));
ChainPolicy.ExtraStore.Clear();
}
catch (Exception ex)
{
Trace.Write(ex);
}
}
}
在调用函数中,我现在可以成功地检查未知证书是否来自国家根证书。
bool bChainOK = false;
using (X509TestChain oChain = new X509TestChain(oCert))
{
if ((oChain.ChainElements.Count > 0)
&& IsPKIOverheidRootCert(oChain.ChainElements[oChain.ChainElements.Count - 1].Certificate))
bChainOK = true;
if (!bChainOK)
{
TraceChain(oChain);
sMessage = "Root certificate not present or not PKI Overheid (Staat der Nederlanden)";
return false;
}
}
return true;
补充说明一下:为了检查根证书(通常已安装,因为它包含在Windows更新中,但理论上也可能缺失),我会将友好名称和指纹与公布的值进行比较。
private static bool IsPKIOverheidRootCert(X509Certificate2 oCert)
{
if (oCert != null)
{
string sFriendlyName = oCert.FriendlyName;
if ((sFriendlyName.IndexOf("Staat der Nederlanden") >= 0)
&& (sFriendlyName.IndexOf(" Root CA") >= 0))
{
switch (oCert.Thumbprint)
{
case "101DFA3FD50BCBBB9BB5600C1955A41AF4733A04":
case "59AF82799186C7B47507CBCF035746EB04DDB716":
case "76E27EC14FDB82C1C0A675B505BE3D29B4EDDBBB":
return true;
}
}
}
return false;
}
我不确定这个检查是否安全,但在我的情况下,Windows Forms应用程序的操作员非常确定可以访问有效证书进行安装。该软件的目标仅是过滤证书列表,以帮助他仅在计算机的机器存储中安装正确的证书(该软件还安装中间和根证书的公钥,以确保Web服务客户端的运行时行为正确)。
PkixCertPathBuilder
API怎么样? - Jaime Hablutzel