CertificateManager.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Text;
  8. using SuperSocket.Common;
  9. using SuperSocket.SocketBase.Config;
  10. namespace SuperSocket.SocketBase.Security
  11. {
  12. static class CertificateManager
  13. {
  14. internal static X509Certificate Initialize(ICertificateConfig cerConfig, Func<string, string> relativePathHandler)
  15. {
  16. if (!string.IsNullOrEmpty(cerConfig.FilePath))
  17. {
  18. //To keep compatible with website hosting
  19. string filePath;
  20. if (Path.IsPathRooted(cerConfig.FilePath))
  21. filePath = cerConfig.FilePath;
  22. else
  23. {
  24. filePath = relativePathHandler(cerConfig.FilePath);
  25. }
  26. return new X509Certificate2(filePath, cerConfig.Password, cerConfig.KeyStorageFlags);
  27. }
  28. else
  29. {
  30. var storeName = cerConfig.StoreName;
  31. if (string.IsNullOrEmpty(storeName))
  32. storeName = "Root";
  33. var store = new X509Store(storeName, cerConfig.StoreLocation);
  34. store.Open(OpenFlags.ReadOnly);
  35. var cert = store.Certificates.OfType<X509Certificate2>().Where(c =>
  36. c.Thumbprint.Equals(cerConfig.Thumbprint, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
  37. store.Close();
  38. return cert;
  39. }
  40. }
  41. }
  42. }