LoginSignup
36
35

More than 5 years have passed since last update.

TLS1.2サポートするサーバとのHTTPS通信実装

Posted at

SSL3.0、TLS1.0、TLS1.1の脆弱性が発見され、TLS1.2に移行するWebサイトが多数あります。TLS1.2の移行に伴い、SSL3.0、TLS1.0、TLS1.1の入り口も残していれば問題ないが、廃止された場合、いままで外部からHTTPS通信でAPI連携するプログラムも書き換える必要があります。

従来TLS1.0のみ対応の場合

/// <summary>
/// Get Response From TLS Support Server
/// </summary>
private void GetDataByHttps()
{
      ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
      try
      {
            var client = new HttpClient();
            var res = await client.GetAsync("https://対象サイトFQDN/");
            res.Dump();
      }
      catch (Exception e)
      {
            logger.Write("Exception:" + e.ToString());
      }
}

TLS1.2に移行後、TLS1.0、TLS1.1が廃止された場合、下記のような例が出力される
System.Net.WebException: 接続が切断されました: 送信時に、予期しないエラーが発生しました。。
---> System.IO.IOException: リモート パーティがトランスポート ストリームを終了したため、認証に失敗しました。
場所 System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
・・・

解決するには、.NET4.5を利用し、Tls1.2のSecurityProtocolを利用
.NET 4.0 supports up to TLS 1.0 while .NET 4.5 supports up to TLS 1.2

/// <summary>
/// Get Response From TLS or Above Support Server
/// </summary>
private void GetDataByHttpsTls10Above()
{
      ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
      try
      {
            var client = new HttpClient();
            var res = await client.GetAsync("https://対象サイトFQDN/");
            res.Dump();
      }
      catch (Exception e)
      {
            logger.Write("Exception:" + e.ToString());
      }
}

.NET4.0以下で対応したい場合、自前でポートを定義


/// <summary>
/// Get Response From TLS or Above Support Server with .Net 3.5 or 4.0
/// </summary>
private void GetDataByHttpsTls10Above()
{
      ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
      try
      {
            var client = new HttpClient();
            var res = await client.GetAsync("https://対象サイトFQDN/");
            res.Dump();
      }
      catch (Exception e)
      {
            logger.Write("Exception:" + e.ToString());
      }
}

対象サーバがTLSをどこまでサポートしているか以下分析サービスを利用するとわかりやすい
https://www.ssllabs.com/ssltest/analyze.html?d=office.yahoo.co.jp
※d=の次にはFQDNをくっつけます。
yahooの例、TLS1.2も対応済みですが、既存のSSL、TLS1.0、TLS1.1もそのまま維持
yahoo.png

36
35
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
35