簡體   English   中英

SSL證書預取.NET

[英]SSL certificate pre-fetch .NET

我正在編寫一個實用程序,可以讓我監控我們網站的健康狀況。 這包括一系列可以針對Web應用程序運行的驗證任務。 其中一項測試是預測特定SSL證書的到期。

我正在尋找一種方法來預先使用.NET或WINAPI獲取安裝在網站上的SSL證書,以便我可以驗證與特定網站關聯的證書的到期日期。

我可以這樣做的一種方法是在ServicePointManager.ServerCertificateValidationCallback處理程序中驗證證書時對證書進行緩存,然后將它們與配置的網站進行匹配,但這似乎有些過時了。 另一種方法是使用網站證書配置應用程序,但我寧願避免這種情況,以便最大限度地減少配置。

對於我來說,使用.NET下載與網站關聯的SSL證書最簡單的方法是什么,以便我可以檢查證書包含的信息來驗證它?

編輯:

要擴展下面的答案,不需要在創建請求之前手動創建ServicePoint。 它作為執行請求的一部分在請求對象上生成。

    private static string GetSSLExpiration(string url)
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        using (WebResponse response = request.GetResponse()) { }
        if (request.ServicePoint.Certificate != null)
        {
            return request.ServicePoint.Certificate.GetExpirationDateString();
        }
        else
        {
            return string.Empty;
        }
    }

我剛試過這個,“在我的機器上工作(tm)”。

它返回表示服務器證書上的到期日期的文本字符串,並要求在網站上進行實際命中。

private string GetSSLExpiryDate(string url)
{
    Uri u = new Uri(url);
    ServicePoint sp = ServicePointManager.FindServicePoint(u);

    string groupName = Guid.NewGuid().ToString();
    HttpWebRequest req = HttpWebRequest.Create(u) as HttpWebRequest;
    req.ConnectionGroupName = groupName;

    using (WebResponse resp = req.GetResponse())
    {
        // Ignore response, and close the response.
    }
    sp.CloseConnectionGroup(groupName);

    // Implement favourite null check pattern here on sp.Certificate
    string expiryDate = sp.Certificate.GetExpirationDateString();

    return expiryDate;
}

我擔心我不知道使用ServicePoint的所有權利和錯誤,以及您可能需要跳過的任何其他箍,但您確實獲得了想要了解的實際網站的SSL到期日期。

編輯:確保“url”參數使用https://協議。

例如string contosoExpiry = GetSSLExpiryData(“ https://www.contoso.com/ ”);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM