2017-08-03 124 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>