Advertisement
tolikpunkoff

Self-signed certificate using to HttpWebRequest

Jan 9th, 2020
1,270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.64 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;
  5. using System.Net.Security;
  6. using System.IO;
  7. using System.Security.Cryptography.X509Certificates;
  8.  
  9. namespace TestApp
  10. {
  11.     class SendRequest
  12.     {
  13.         public delegate void OnConnecting(object sender);                
  14.         public event OnConnecting Connecting;        
  15.        
  16.         private HttpWebRequest request = null;
  17.         private WebProxy proxy = null;        
  18.        
  19.         public string URL { get; set; }
  20.         public string OutputFile { get; set; }
  21.         public string Method { get; set; }
  22.         public string CertHashString { get; set; }
  23.  
  24.         public NetConnectionType ConnectionType { get; set; }
  25.         public string ProxyAddress { get; set; }
  26.         public int ProxyPort { get; set; }
  27.         public string ProxyUser { get; set; }
  28.         public string ProxyPassword { get; set; }        
  29.         public int ConnectionTimeout { get; set; }
  30.  
  31.         public string ErrorMessage { get; private set; }
  32.        
  33.         public SendRequest(string url, string outputfile)
  34.         {
  35.             URL = url;
  36.             OutputFile = outputfile;
  37.             Method = "GET";
  38.  
  39.             DisableIgnoreCertError();
  40.             DisableValidateCert();
  41.         }
  42.  
  43.         public void EnableIgnoreCertError()
  44.         {
  45.             ServicePointManager.ServerCertificateValidationCallback =
  46.                 delegate { return true; };
  47.         }
  48.  
  49.         public void DisableIgnoreCertError()
  50.         {
  51.             ServicePointManager.ServerCertificateValidationCallback = null;
  52.         }
  53.  
  54.         public void EnableValidateCert()
  55.         {
  56.             ServicePointManager.ServerCertificateValidationCallback =
  57.                 ValidateCert;
  58.            
  59.         }
  60.  
  61.         public void DisableValidateCert()
  62.         {
  63.             ServicePointManager.ServerCertificateValidationCallback = null;
  64.         }
  65.  
  66.         private bool ValidateCert(object sender, X509Certificate cert,
  67.             X509Chain chain, SslPolicyErrors sslPolicyErrors)
  68.         {
  69.             //все и так хорошо
  70.             if (sslPolicyErrors == SslPolicyErrors.None)
  71.             {
  72.                 return true;
  73.             }
  74.  
  75.             //не передан хэш сертификата
  76.             //значит и проверять нечего
  77.             if (string.IsNullOrEmpty(CertHashString))
  78.             {
  79.                 return false;
  80.             }
  81.  
  82.             //получаем хэш сертификата сервера в виде строки
  83.             string hashstring = cert.GetCertHashString();
  84.  
  85.             //если хэши полученного и известного
  86.             //сертификата совпадают - все ок.
  87.             if (hashstring == CertHashString)
  88.             {
  89.                 return true;
  90.             }
  91.  
  92.             return false;
  93.         }
  94.  
  95.         public bool CreateRequest()
  96.         {
  97.             //устанавливаем минимальные параметры для запроса
  98.             try
  99.             {
  100.                 request = (HttpWebRequest)HttpWebRequest.Create(URL);
  101.             }
  102.             catch (Exception ex)
  103.             {
  104.                 ErrorMessage = "Request Error: " + ex.Message;                
  105.                 return false;
  106.             }
  107.  
  108.             switch (ConnectionType)
  109.             {
  110.                 case NetConnectionType.NoProxy:
  111.                     {
  112.                         proxy = null;
  113.                         HttpWebRequest.DefaultWebProxy = null;
  114.                         request.Proxy = proxy;
  115.                     }; break;
  116.  
  117.                 case NetConnectionType.SystemProxy:
  118.                     {
  119.                         HttpWebRequest.DefaultWebProxy = HttpWebRequest.GetSystemWebProxy();
  120.                         proxy = null;
  121.                     }; break;
  122.                 case NetConnectionType.ManualProxy:
  123.                     {
  124.                         proxy = new WebProxy(ProxyAddress, ProxyPort);
  125.                         if (!string.IsNullOrEmpty(ProxyUser)) //есть имя пользователя, надобно авторизоваться
  126.                         {
  127.                             CredentialCache cred = new CredentialCache();
  128.                             cred.Add(ProxyAddress, ProxyPort, "Basic",
  129.                                 new NetworkCredential(ProxyUser, ProxyPassword));
  130.  
  131.                             proxy.Credentials = cred;
  132.                         }
  133.  
  134.                         request.Proxy = proxy;
  135.                     }; break;
  136.             }
  137.  
  138.  
  139.             if (ConnectionTimeout > 0) request.Timeout = ConnectionTimeout;
  140.             request.Method = Method;
  141.  
  142.             return true;
  143.         }
  144.        
  145.         public bool Send()
  146.         {
  147.             if (Connecting != null) Connecting(this);
  148.            
  149.             //получаем ответ
  150.             HttpWebResponse resp = null;
  151.             FileStream writeStream = null;            
  152.             try
  153.             {
  154.                 resp = (HttpWebResponse)request.GetResponse();
  155.                 //не вывалились в ошибку, значит все OK
  156.  
  157.                 //заводим поток для записи выходного файла
  158.                 writeStream = new FileStream(OutputFile, FileMode.Create);
  159.                 int size = 1024; //размер буфера для обмена между потоками
  160.                 byte[] buf = new byte[size]; //буфер
  161.                 int count = 0; //для хранения фактически прочитанных байт
  162.  
  163.                 //получаем поток ответа
  164.                 Stream RespStream = resp.GetResponseStream();
  165.  
  166.                 //пишем данные в файл
  167.                 do
  168.                 {
  169.                     count = RespStream.Read(buf, 0, size); //читаем кусками == size
  170.  
  171.                     if (count > 0) //данные есть?
  172.                     {
  173.                         writeStream.Write(buf, 0, count); //пишем фактически
  174.                         //прочитанное кол-во байт
  175.                     }
  176.                 } while (count > 0);
  177.                 writeStream.Close(); //закрываем поток записи, сохраняем файл
  178.             }
  179.             catch (WebException webex)
  180.             {
  181.                 //вылетели в ошибку веба - пытаемся закрыть поток
  182.                 if (writeStream != null) writeStream.Close();
  183.  
  184.                 ErrorMessage = webex.Message;
  185.  
  186.                 if (webex.Status == WebExceptionStatus.ProtocolError)
  187.                 {
  188.                     //ошибка протокола (404, например)
  189.                     //интернет может и есть
  190.                     ErrorMessage = "Protocol Error: " + ErrorMessage;
  191.                     return false;
  192.                 }
  193.                 else //какая-то другая ошибка интернетов
  194.                 {
  195.                     ErrorMessage = "Network Error: " + ErrorMessage;
  196.                     return false;
  197.                 }
  198.             }
  199.             catch (Exception ex) //другая ошибка (напр. I/O error)
  200.             {
  201.                 //пытаемся закрыть поток
  202.                 if (writeStream != null) writeStream.Close();                
  203.                 ErrorMessage = "Other Error: " + ex.Message;
  204.                 return false;
  205.             }
  206.  
  207.             return true;
  208.         }                
  209.     }
  210. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement