如何通过X509Certificate2Collection链验证X509Certificate2

| 我正在编写一个SAML 2.0响应解析器,以处理ASP.Net中的POST身份验证(在C#和MVC中,但这不太重要)。 因此,我有一个用于验证的ѭ0and文件,可以将其读取为
X509Certificate2Collection
和一个示例断言-基于64位编码的SAML响应。 理想情况下,我想使用内置的
WSSecurityTokenSerializer
,但是失败了,所以我正在寻找一种可行的方法。 我正在直接阅读XML:
// get the base 64 encoded SAML
string samlAssertionRaw = GetFromHttpRequest();

// load a new XML document
var assertion = new XmlDocument { PreserveWhitespace = true };
assertion.LoadXml(samlAssertionRaw);

// use a namespace manager to avoid the worst of xpaths
var ns = new XmlNamespaceManager(assertion.NameTable);
ns.AddNamespace(\"samlp\", @\"urn:oasis:names:tc:SAML:2.0:protocol\");
ns.AddNamespace(\"saml\", @\"urn:oasis:names:tc:SAML:2.0:assertion\");
ns.AddNamespace(\"ds\", SignedXml.XmlDsigNamespaceUrl);

// get the signature XML node
var signNode = assertion.SelectSingleNode(
    \"/samlp:Response/saml:Assertion/ds:Signature\", ns);

// load the XML signature
var signedXml = new SignedXml(assertion.DocumentElement);
signedXml.LoadXml(signNode as XmlElement);

// get the certificate, basically:
// signedXml.KeyInfo.OfType<KeyInfoX509Data>().First().
//     Certificates.OfType<X509Certificate2>().First()
// but with added checks
var certificate = GetFirstX509Certificate(signedXml);

// check the key and signature match
if (!signedXml.CheckSignature(certificate, true))
{
    throw new SecurityException(\"Signature check failed.\");
}

// go on and read the SAML attributes from the XML doc
这个工作可行,但要做的只是检查签名和SAML响应中的“ 4”公钥是否匹配。它不会以任何方式验证其来源,因此我需要在接受SAML身份验证之前执行此操作。 似乎有两种方法可以检查SAML响应中找到的证书-我可以执行
certificate.Verify()
,也可以使用签名为
signedXml.CheckSignature(certificate, false)
进行检查。 但是,两者都返回false。 我认为这是因为正在针对他们的机器商店进行检查,或者可能是在线检查(我不确定如何检查)。我想对照从
.p7b
文件检索的
X509Certificate2Collection
检查它们-应该忽略在计算机上注册的证书,而只检查
.p7b
证书。 似乎没有任何方法可以将ѭ1传递给ѭ11或
CheckSignature
方法。 这是对SAML响应进行的正确检查吗? 有什么方法可以使用我想使用的“ 0”证书吗?     
已邀请:
您是否尝试过使用自定义的
X509Chain
配置为在验证过程中搜索an15个证书。类似于以下内容:
// Placeholder for the certificate to validate
var targetCertificate = new X509Certificate2();
// Placeholder for the extra collection of certificates to be used
var certificates = new X509Certificate2Collection();

var chain = new X509Chain();

chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.ExtraStore.AddRange(certificates);

bool isValidCertificate = chain.Build(targetCertificate);
在该示例中,吊销检查也被禁用,但是如果您具有对CRL的在线或脱机访问权限,则可以启用它。 “ 15”应允许包括不在机器/用户存储中的中间证书。但是,取决于
X509Chain
中指定的证书,受信任的根证书可能需要位于计算机或用户存储中,因为否则将导致
UntrustedRoot
失败。如果连根都无法在计算机或用户存储中使用,则可以尝试遍历生成的链,并确保唯一的错误是由于不可信的根所致,同时还要确保链根就是您要使用的根会根据您用于验证的ѭ1期望。 或者,您可以创建自己的自定义“ 21”来仅考虑提供的“ 1”来验证证书。     

要回复问题请先登录注册