小编典典

在.NET的HttpWebRequest / Response中使用自签名证书

c#

我正在尝试连接到使用自签名SSL证书的API。我这样做是使用.NET的HttpWebRequest和HttpWebResponse对象。我得到一个例外:

基础连接已关闭:无法为SSL / TLS安全通道建立信任关系。

我明白这意味着什么。而且我明白 为什么 .NET认为它应该警告我并关闭连接。但是在这种情况下,无论如何,我还是想连接到API,这是该死的中间人攻击。

那么,如何为该自签名证书添加例外?还是告诉HttpWebRequest / Response根本不验证证书的方法?我该怎么做?


阅读 569

收藏
2020-05-19

共1个答案

小编典典

@Domster:可以,但是您可能想通过检查证书哈希是否符合您的期望来加强安全性。因此,扩展版本看起来像这样(基于我们正在使用的一些实时代码):

static readonly byte[] apiCertHash = { 0xZZ, 0xYY, ....};

/// <summary>
/// Somewhere in your application's startup/init sequence...
/// </summary>
void InitPhase()
{
    // Override automatic validation of SSL server certificates.
    ServicePointManager.ServerCertificateValidationCallback =
           ValidateServerCertficate;
}

/// <summary>
/// Validates the SSL server certificate.
/// </summary>
/// <param name="sender">An object that contains state information for this
/// validation.</param>
/// <param name="cert">The certificate used to authenticate the remote party.</param>
/// <param name="chain">The chain of certificate authorities associated with the
/// remote certificate.</param>
/// <param name="sslPolicyErrors">One or more errors associated with the remote
/// certificate.</param>
/// <returns>Returns a boolean value that determines whether the specified
/// certificate is accepted for authentication; true to accept or false to
/// reject.</returns>
private static bool ValidateServerCertficate(
        object sender,
        X509Certificate cert,
        X509Chain chain,
        SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
    {
        // Good certificate.
        return true;
    }

    log.DebugFormat("SSL certificate error: {0}", sslPolicyErrors);

    bool certMatch = false; // Assume failure
    byte[] certHash = cert.GetCertHash();
    if (certHash.Length == apiCertHash.Length)
    {
        certMatch = true; // Now assume success.
        for (int idx = 0; idx < certHash.Length; idx++)
        {
            if (certHash[idx] != apiCertHash[idx])
            {
                certMatch = false; // No match
                break;
            }
        }
    }

    // Return true => allow unauthenticated server,
    //        false => disallow unauthenticated server.
    return certMatch;
}
2020-05-19