使用C#验证SSL证书

时间:2019-01-20 16:20:39

标签: c# unity3d ssl https certificate

我正在尝试使用SSL与后端服务器通信。 我正在尝试使用System.Net.Http库中的HttpClient,但无法正常工作。 这是我的代码(自从我使用Unity以来,Debug.Log只是打印内容):

public static async Task DownloadPageAsync(string web)
 {
     try
     {
         HttpClient cl = new HttpClient();
         string body = await cl.GetStringAsync(new Uri(web));

         Debug.Log(web);
     }
     catch (HttpRequestException e)
     {
         Debug.Log(e.InnerException.Message);
     }
     catch (Exception ex)
     {
         Debug.Log(ex.ToString());
     }
 }

当我在证书错误的Web上尝试使用它时,它会显示:“错误:TrustFailure(身份验证或解密失败。)”,这很好。问题在于,好的证书还会触发错误:“错误:SecureChannelFailure(身份验证或解密失败。)”。

我看到其他答案说,简单地接受所有证书就可以了,但是我需要检查它是否是有效证书。

??是否可以使用HttpClient执行此操作?或其他班级?

顺便说一句,我只用它来发送POST请求,并接收一个简单的字符串。

谢谢!

1 个答案:

答案 0 :(得分:0)

对于UnityWebRequest,自Unity 2018.1起就有UnityWebRequest.certificateHandler,例如

IEnumerator GetRequest(string uri)
{
     UnityWebRequest request = UnityWebRequest.Get(uri);
     request.certificateHandler = new AcceptAllCertificatesSignedWithASpecificPublicKey();

     yield return request.SendWebRequest ();
     if (request.isNetworkError)
     {
         Debug.Log("Something went wrong, and returned error: " + request.error);
     }
     else
     {
         // Show results as text
         Debug.Log(request.downloadHandler.text);
     }
}

示例CertificateHandler的实现:

using UnityEngine.Networking;
using System.Security.Cryptography.X509Certificates;
using UnityEngine;
// Based on https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#.Net
class AcceptAllCertificatesSignedWithASpecificPublicKey: CertificateHandler
{
    // Encoded RSAPublicKey
    private static string PUB_KEY = "mypublickey";
    protected override bool ValidateCertificate(byte[] certificateData)
    {
        X509Certificate2 certificate = new X509Certificate2(certificateData);
        string pk = certificate.GetPublicKeyString();
        if (pk.ToLower().Equals(PUB_KEY.ToLower()))
        {
            return true;
        }

        return false;
    }
}

Source


对于HttpClient,请参见Make Https call using HttpClient