首页 > 解决方案 > 当我有可用的公钥、私钥和 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 安全通道。' ”。

标签: c#winformsopensslssl-certificatehttpwebrequest

解决方案


无法使其与 .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) {
            //
        }

推荐阅读