首页 > 解决方案 > 使用 C# 验证 SSL 证书

问题描述

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

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());
     }
 }

当我在证书错误的网络中尝试它时,它给出:“错误:TrustFailure(身份验证或解密失败。)”,这很好。问题是好的证书也会触发错误:“错误:SecureChannelFailure(身份验证或解密失败。)”。

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

¿ 有没有办法用 HttpClient 做到这一点?¿ 或与其他班级?

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

谢谢!

标签: c#unity3dsslhttpscertificate

解决方案


因为UnityWebRequest因为Unity 2018.1UnityWebRequest.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;
    }
}

来源


HttpClient参阅使用 HttpClient 进行 Https 调用


推荐阅读