![](/img/trans.png)
[英]How do I programmatically remove a certificate in Trusted Root Certification Authorities?
[英]How do I validate that a certificate was created by a particular certification authority?
我有一個Windows證書頒發機構,我用它來通過.net / c#發出客戶端身份驗證證書。 通過COM調用證書頒發機構的API,我已經能夠成功地以編程方式頒發證書。 我在設置客戶端時發出新證書。
在運行時,這些客戶端將證書附加到我的服務器的請求。 如何以編程方式驗證X509Certificate2是否由我的證書頒發機構的根證書簽名(並拒絕由任何其他來源簽名的證書)?
我做了很多 。 這里有一些你可以使用的簡單代碼。
if (!isChainValid)
塊中的部分是一個非常錯誤的消息。 如果您不想要,則不必使用它,但如果無法構建鏈,則應該拋出錯誤。 鏈元素是檢查根的必要條件。
X509Certificate2 authority = GetAuthorityCertificate();
X509Certificate2 certificateToValidate = GetCertificateToValidate();
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
chain.ChainPolicy.VerificationTime = DateTime.Now;
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);
// This part is very important. You're adding your known root here.
// It doesn't have to be in the computer store at all. Neither certificates do.
chain.ChainPolicy.ExtraStore.Add(authority);
bool isChainValid = chain.Build(certificateToValidate);
if (!isChainValid)
{
string[] errors = chain.ChainStatus
.Select(x => String.Format("{0} ({1})", x.StatusInformation.Trim(), x.Status))
.ToArray();
string certificateErrorsString = "Unknown errors.";
if (errors != null && errors.Length > 0)
{
certificateErrorsString = String.Join(", ", errors);
}
throw new Exception("Trust chain did not complete to the known authority anchor. Errors: " + certificateErrorsString);
}
// This piece makes sure it actually matches your known root
var valid = chain.ChainElements
.Cast<X509ChainElement>()
.Any(x => x.Certificate.Thumbprint == authority.Thumbprint);
if (!valid)
{
throw new Exception("Trust chain did not complete to the known authority anchor. Thumbprints did not match.");
}
您還可以使用X509Certificate2
的內置方法Verify()
。
X509Certificate2 certificateToValidate = GetCertificateToValidate();
bool valid = certificateToValidate.Verify()
如果您說您有一個root (自簽名)證書,那么您唯一的選擇是在服務器上保留此根證書(當然沒有私鑰)並對您的根證書執行證書驗證程序。 這是Web客戶端驗證服務器證書鏈的鏡像情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.