如何在 .NET Framework 4.0, 4.5 以上的程式支援 TLS 1.2


情境

在 .NET Framework 4.0 中沒有SecurityProtocolType.Tls1.2 的列舉型態可以使用,要在 .NET Framework 4.5 以上的版本才有 Tls1.2 可以使用。

參考資訊:

.NET Framework 4.0 中沒有SecurityProtocolType.Tls1.2

https://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.100).aspx

.NET Framework 4.5中有SecurityProtocolType.Tls1.2

https://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx

 

寫到這裡,好像要使用TLS1.2 程式一定要升版到 .NET Framework 4.5 或更新版本?

 

請先安裝 .NET Framework 4.5.2 以上版本 runtime, 程式不用重新編譯成新版

下列的兩個方法,選一個實作即可


方法1:

提供一個範例通用在 .NET 4.0 以上的版本:

using System;

using System.IO;

using System.Net;

using System.Net.Security;

using System.Security.Cryptography.X509Certificates;

using System.Text;

 

namespace Examples.System.Net

{

public class WebRequestGetExample

{

public static void Main()

{

// Create a request for the URL.

WebRequest request = WebRequest.Create(“https://yourtesturl“);

// If required by the server, set the credentials.

request.Credentials = CredentialCache.DefaultCredentials;

 

            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);

// 重點是修改這行

            ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2;

 

// Get the response.

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

// Display the status.

Console.WriteLine(response.StatusDescription);

// Get the stream containing content returned by the server.

Stream dataStream = response.GetResponseStream();

// Open the stream using a StreamReader for easy access.

StreamReader reader = new StreamReader(dataStream);

// Read the content.

string responseFromServer = reader.ReadToEnd();

// Display the content.

Console.WriteLine(responseFromServer);

// Cleanup the streams and the response.

reader.Close();

dataStream.Close();

response.Close();

}

 

private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)

{

return true;

}

}

}

 


方法2:

在我的lab 中直接修改下列兩個 Registry Key 後,可以直接使用 TLS 1.2 連接不用改程式。

 

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]

“SchUseStrongCrypto”=dword:00000001

Reg01

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]

“SchUseStrongCrypto”=dword:00000001

Reg02

 

ServicePointManager 程式碼:

http://referencesource.microsoft.com/#System/net/System/Net/ServicePointManager.cs,3528c78e8b71ece2

依原始程式碼做了一張流程圖如下:

TLS_NET

 

結論:如果無法動程式,直接更新.NET Framework 4.5.2 或更新, 再新增2 個 Registry Key


Comments (0)

Skip to main content