You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.1 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Security;
  5. using System.Security.Cryptography.X509Certificates;
  6. using System.Text;
  7. namespace Apewer.Network
  8. {
  9. /// <summary></summary>
  10. public static class SslUtility
  11. {
  12. /// <summary>证书验证回调。</summary>
  13. private static RemoteCertificateValidationCallback ValidationCallback
  14. {
  15. get { return ServicePointManager.ServerCertificateValidationCallback; }
  16. set { ServicePointManager.ServerCertificateValidationCallback = value; }
  17. }
  18. /// <summary>证书验证。忽略所有错误。</summary>
  19. public static bool ApproveAll(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  20. {
  21. return true;
  22. }
  23. /// <summary>证书验证。</summary>
  24. public static X509Certificate ApproveFirst(object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers)
  25. {
  26. if (localCertificates != null)
  27. {
  28. for (var i = 0; i < localCertificates.Count; i++)
  29. {
  30. var certificate = localCertificates[i];
  31. if (certificate != null) return certificate;
  32. }
  33. }
  34. return null;
  35. }
  36. /// <summary>证书验证。要求必须有正确的证书。</summary>
  37. public static bool ApproveRight(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  38. {
  39. return (errors == SslPolicyErrors.None) ? true : false;
  40. }
  41. /// <summary>设置可通用的证书验证回调。</summary>
  42. /// <param name="all">批准所有验证,指定为 FALSE 时将要求系统验证。</param>
  43. public static void ApproveValidation(bool all = true)
  44. {
  45. if (all) ValidationCallback = new RemoteCertificateValidationCallback(ApproveAll);
  46. else ValidationCallback = new RemoteCertificateValidationCallback(ApproveRight);
  47. }
  48. }
  49. }