18
19

More than 5 years have passed since last update.

Unity C# HttpwebRequestでhttps通信(オレオレ証明書エラーを回避)

Last updated at Posted at 2015-07-29

■普通にHttpsありのURLを書くと下記エラーになる。

 TlsException: Invalid certificate received from server. Error code: 0xffffffff800b010f

■.Net新しいバージョン用

こちらのページを参考にしました。
http://www.atmarkit.co.jp/fdotnet/dotnettips/867sslavoidverify/sslavoidverify.html

■usingを追加

using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

■SSL証明書のコールバック用の関数

    // 信頼できないSSL証明書を「問題なし」にするメソッド
    private bool OnRemoteCertificateValidationCallback(
      Object sender,
      X509Certificate certificate,
      X509Chain chain,
      SslPolicyErrors sslPolicyErrors)
    {
        return true;  // 「SSL証明書の使用は問題なし」と示す
    }

■SSL証明書のバリデーションに先ほど作ったメソッドをコールバック登録

ServicePointManager.ServerCertificateValidationCallback =
     new RemoteCertificateValidationCallback(OnRemoteCertificateValidationCallback);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URLをここに書く);

■.Net古いバージョン用

こちらのページを参考にしました。
http://masa795.hatenablog.jp/entry/2013/07/08/214336

■強制的にTrueを返すクラスを作成

TrustAllCertificatePolicy.cs
using UnityEngine;
using System.Collections;

public class TrustAllCertificatePolicy : System.Net.ICertificatePolicy {

    public TrustAllCertificatePolicy() { }
    public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert,
        System.Net.WebRequest req,
        int problem)
    {
        return true;
    }
}

■Createの前に設定しておく

System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URLをここに書く);
18
19
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
18
19