c# - 当我有可用的公钥、私钥和 ca 文件时,如何从 HTTPS 自签名网页中检索 (GET) 数据?
问题描述
我正在尝试从 https 网站获取一些数据,并且我确实有凭据(公钥和私钥)以及相同的 ca。我怎样才能做到这一点?
我试过这样做但没有成功
private string RetrieveSoftwareDataMsgFromURL() {
var cacert = File.ReadAllText(@"Certs\ca.crt");
var clientcert = File.ReadAllText(@"Certs\client.crt");
var clientkey = File.ReadAllText(@"Certs\client.key");
ServicePointManager.Expect100Continue = true;
ServicePointManager.DefaultConnectionLimit = 9999;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |SecurityProtocolType.Tls |SecurityProtocolType.Tls11 |SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
ICertificateProvider provider = new CertificateFromFileProvider(clientcert, clientkey);
X509Certificate2 clientCertificate = provider.Certificate;
string url = "https://SomeWebsite.com/changelog";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
httpWebRequest.AuthenticationLevel = AuthenticationLevel.MutualAuthRequired;
httpWebRequest.ClientCertificates.Add(clientCertificate);
httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
string result = "Nothing's In There";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) {
result = streamReader.ReadLine();
}
return result;
}
我最终遇到了这个异常“System.Net.WebException:'请求被中止:无法创建 SSL/TLS 安全通道。' ”。
解决方案
无法使其与 .crt 和 .key 文件一起使用,但尝试使用证书创建 .pfx 文件,然后尝试以下操作;
WebRequestHandler handler = new WebRequestHandler();
handler.ClientCertificates.Add(cert);
HttpClient client = new HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan };
try {
var httpResponse = await client.GetAsync(URL) as HttpResponseMessage;
using (var remoteStream = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (var content = File.Create(filepath)) {
var buffer = new byte[4096];
int read;
while ((read = await remoteStream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) != 0) {
await content.WriteAsync(buffer, 0, read).ConfigureAwait(false);
FlushFileBuffers(content.SafeFileHandle);
}
}
} catch (Exception e) {
//
}
推荐阅读
- react-router - 仅当路由参数与枚举值匹配时才匹配路由
- odbc - 是否可以通过 ODBC 驱动程序将 Power BI 连接到 kdb 数据库?
- ibm-mobilefirst - CDI 在简单的适配器中不起作用
- java - Java 8 Streams:获取非重复计数
- android - 带有 TYPE_SYSTEM_ALERT 的视图中的工具栏
- node.js - 特定域的特定电子邮件的正则表达式
- sql - SQL 查询以获取特定序列号的具有特定特征的最新测试记录
- javascript - 如何使用 Vue 组件进行 eslint?
- sql - 检查哪些视图有行
- javascript - 返回滚动位置javascript