c# - 使用 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 请求,并接收一个简单的字符串。
谢谢!
解决方案
因为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;
}
}
(来源)
请HttpClient
参阅使用 HttpClient 进行 Https 调用
推荐阅读
- objective-c - 是否可以从同一个工作区中的不同项目访问一个类?
- python - 支持向量回归中的 epsilon 是否应该缩放?
- flutter - Flutter - 在 setState 更改其位置后获取 RenderBox 位置
- hibernate - 我有没有办法将代码转换为使用批处理,以便立即执行并提高性能?
- laravel - Laravel 文件缓存:我们可以设置文件权限吗?
- c# - 此元素的 Xpath 或 Css 选择器 - HELPP
- vb.net - 循环中的局部字符串变量初始化
- outlook - OfficeJS - Outlook 插件
- python - 超时后强制获取输入
- sql - “=”/like子句中存储过程中的正则表达式