Default SecurityProtocol in .NET 4.5

前端 未结 17 1387
一生所求
一生所求 2020-11-22 03:24

What is the default security protocol for communicating with servers that support up to TLS 1.2? Will .NET by default, choose the highest security

17条回答
  •  逝去的感伤
    2020-11-22 04:11

    Following code will:

    • print enabled protocols
    • print available protocols
    • enable TLS1.2 if platform supports it and if it is not enabled to begin with
    • disable SSL3 if it is enabled
    • print end result

    Constants:

    • 48 is SSL3
    • 192 is TLS1
    • 768 is TLS1.1
    • 3072 is TLS1.2

    Other protocols will not be affected. This makes this compatible with future protocols (Tls1.3, etc).

    Code

    // print initial status
        Console.WriteLine("Runtime: " + System.Diagnostics.FileVersionInfo.GetVersionInfo(typeof(int).Assembly.Location).ProductVersion);
        Console.WriteLine("Enabled protocols:   " + ServicePointManager.SecurityProtocol);
        Console.WriteLine("Available protocols: ");
        Boolean platformSupportsTls12 = false;
        foreach (SecurityProtocolType protocol in Enum.GetValues(typeof(SecurityProtocolType))) {                
            Console.WriteLine(protocol.GetHashCode());
            if (protocol.GetHashCode() == 3072){
                platformSupportsTls12 = true;
            }
        }
        Console.WriteLine("Is Tls12 enabled: " + ServicePointManager.SecurityProtocol.HasFlag((SecurityProtocolType)3072));    
    
    
    // enable Tls12, if possible
        if (!ServicePointManager.SecurityProtocol.HasFlag((SecurityProtocolType)3072)){
            if (platformSupportsTls12){
                Console.WriteLine("Platform supports Tls12, but it is not enabled. Enabling it now.");
                ServicePointManager.SecurityProtocol |= (SecurityProtocolType)3072;
            } else {
                Console.WriteLine("Platform does not supports Tls12.");
            }
        }
    
    // disable ssl3
       if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Ssl3)) { 
          Console.WriteLine("Ssl3SSL3 is enabled. Disabling it now.");
          // disable SSL3. Has no negative impact if SSL3 is already disabled. The enclosing "if" if just for illustration.
          System.Net.ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;                      
       }
        Console.WriteLine("Enabled protocols:   " + ServicePointManager.SecurityProtocol);
    

    Output

    Runtime: 4.7.2114.0
    Enabled protocols:   Ssl3, Tls
    Available protocols: 
    0
    48
    192
    768
    3072
    Is Tls12 enabled: False
    Platform supports Tls12, but it is not enabled. Enabling it now.
    Ssl3 is enabled. Disabling it now.
    Enabled protocols:   Tls, Tls12
    

提交回复
热议问题