Lớp X509Chain
được thiết kế để thực hiện việc này, thậm chí bạn có thể tùy chỉnh cách nó thực hiện quy trình xây dựng chuỗi.
static bool VerifyCertificate(byte[] primaryCertificate, IEnumerable<byte[]> additionalCertificates)
{
var chain = new X509Chain();
foreach (var cert in additionalCertificates.Select(x => new X509Certificate2(x)))
{
chain.ChainPolicy.ExtraStore.Add(cert);
}
// You can alter how the chain is built/validated.
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreWrongUsage;
// Do the validation.
var primaryCert = new X509Certificate2(primaryCertificate);
return chain.Build(primaryCert);
}
Các X509Chain
sẽ chứa thêm thông tin về sự thất bại xác nhận sau khi Build() == false
nếu bạn cần nó.
Chỉnh sửa: Điều này sẽ chỉ đảm bảo rằng CA của bạn hợp lệ. Nếu bạn muốn đảm bảo rằng chuỗi giống hệt nhau, bạn có thể kiểm tra dấu vân tay theo cách thủ công. Bạn có thể sử dụng phương pháp sau đây để đảm bảo rằng các chuỗi xác nhận là đúng, nó sẽ yêu cầu chuỗi theo thứ tự: ..., INTERMEDIATE2, INTERMEDIATE1 (Signer of INTERMEDIATE2), CA (Signer of INTERMEDIATE1)
static bool VerifyCertificate(byte[] primaryCertificate, IEnumerable<byte[]> additionalCertificates)
{
var chain = new X509Chain();
foreach (var cert in additionalCertificates.Select(x => new X509Certificate2(x)))
{
chain.ChainPolicy.ExtraStore.Add(cert);
}
// You can alter how the chain is built/validated.
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreWrongUsage;
// Do the preliminary validation.
var primaryCert = new X509Certificate2(primaryCertificate);
if (!chain.Build(primaryCert))
return false;
// Make sure we have the same number of elements.
if (chain.ChainElements.Count != chain.ChainPolicy.ExtraStore.Count + 1)
return false;
// Make sure all the thumbprints of the CAs match up.
// The first one should be 'primaryCert', leading up to the root CA.
for (var i = 1; i < chain.ChainElements.Count; i++)
{
if (chain.ChainElements[i].Certificate.Thumbprint != chain.ChainPolicy.ExtraStore[i - 1].Thumbprint)
return false;
}
return true;
}
Tôi không thể kiểm tra điều này bởi vì tôi không có một chuỗi CA đầy đủ với tôi , do đó, tốt nhất là gỡ lỗi và bước qua mã.
Nguồn
2011-09-07 10:15:37
làm cách nào để xác minh 3 cùng một lúc? làm thế nào tôi có thể chuỗi 3 certs? – Jacob
Tôi không chắc chắn, nhưng cố gắng tạo cửa hàng tạm thời [X509Store] (http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx). Hơn tất cả các chứng chỉ vào cửa hàng đó. Sau đó, bạn nên gọi xác thực trên chứng chỉ thấp nhất. – MichaelMocko