2017-08-03 120 views
0

我需要将JSON数据发布到TLS 1.2端点。我希望在App.config中指定SecurityProtocol,而不是在源代码中进行硬编码,并且不希望将计算机的注册表设置为禁用TLS 1.1。通过App.config为System.Net.HttpWebRequest指定SSL/TLS

如果您未指定SecurityProtocol,则会使用底层的操作系统协议,但它们似乎默认安全性最低,而不是最安全。因为我有多台服务在机器上运行,所以我无法将操作系统设置为仅使用TLS1.2,但我仍然希望此特定客户机使用TLS 1.2,并且在出现TLS 1.3时,可以通过特定于应用程序的配置对其进行修改。

这个问题介绍了如何通过代码来做到这一点:How to specify SSL protocol to use for WebClient class

这个问题介绍如何通过注册表设置这样做对整个机器:Are there .NET implementation of TLS 1.2?

// this is what I want to avoid 
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocol.Tls12; 

System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url); 

using (System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream())) 
{ 
    sw.write(json); 
} 

System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); 
using System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream())) 
{ 
    content = sr.ReadToEnd(); 
} 

我没有在我的应用程式内容.config目前这个客户端,但这是我想改变。

我发现system.serviceModel内有一个sslStreamSecurity元素,但我相信这是用于ServiceReferences,而不是普通的HttpWebRequest。我相信这是涵盖system.net下,但我找不到相应的。

<system.serviceModel> 
    <bindings> 
    <customBinding> 
     <binding name="myBinding"> 
     <sslStreamSecurity sslProtocls="Tls12"> 
     </binding> 
    </customBinding> 
    </bindings> 
    <client> 
    <endpoint address="https://myserver.com" binding="customBinding" bindingConfiguration="myBinding" name="myEndpoint" /> 
    </client> 
</system.ServiceModel> 

我使用HttpWebRequest的比/ HttpWebResponse其他的东西相当开放,但想从安装第三方软件包望而却步。我从System.Net.Http.HttpClient开始,看起来比HttpWebRequest更新,但很快遇到了相同的问题。

回答

0

现在我已经在App.config中设置了一个整数值,该整数值指定将System.Net.ServicePointManager.SecurityProtocol设置为的枚举值。我仍然认为可能有一个更优雅的方式来做到这一点,并期待其他答案。我被https://stackoverflow.com/a/35325333/5221761

int securityProtocol = Convert.ToInt32(ConfigurationManager.AppSettings["SecurityProtocol"]); 

try 
{ 
    System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)securityProtocol; 
} 
catch(Exception ex) 
{ 
    Console.WriteLine("Could not setup SecurityProtocol. Try a different integer value: " + ex.Message); 
    foreach (System.Net.SecurityProtocolType protocolType in Enum.GetValues(typeof(System.Net.SecurityProtocolType))) 
    { 
     Console.WriteLine(string.Foramt("SecurityProtocol: {0} - {1}", protocolType.ToString(), (int)protocolType)); 
    } 
} 

的App.config在这个方向上引导:

<appSettings> 
    <add key="SecurityProtocol" value="3072" /> 
</appSettings>