CertEnvironment.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using Org.BouncyCastle.X509;
  5. using Alipay.EasySDK.Kernel.Util;
  6. using System.Linq;
  7. namespace Alipay.EasySDK.Kernel
  8. {
  9. /// <summary>
  10. /// 证书模式运行时环境
  11. /// </summary>
  12. public class CertEnvironment
  13. {
  14. /// <summary>
  15. /// 支付宝根证书内容
  16. /// </summary>
  17. public string RootCertContent { get; set; }
  18. /// <summary>
  19. /// 支付宝根证书序列号
  20. /// </summary>
  21. public string RootCertSN { get; set; }
  22. /// <summary>
  23. /// 商户应用公钥证书序列号
  24. /// </summary>
  25. public string MerchantCertSN { get; set; }
  26. /// <summary>
  27. /// 缓存的不同支付宝公钥证书序列号对应的支付宝公钥
  28. /// </summary>
  29. private readonly Dictionary<string, string> CachedAlipayPublicKey = new Dictionary<string, string>();
  30. /// <summary>
  31. /// 构造证书运行环境
  32. /// </summary>
  33. /// <param name="merchantCertPath">商户公钥证书路径</param>
  34. /// <param name="alipayCertPath">支付宝公钥证书路径</param>
  35. /// <param name="alipayRootCertPath">支付宝根证书路径</param>
  36. public CertEnvironment(string merchantCertPath, string alipayCertPath, string alipayRootCertPath)
  37. {
  38. if (string.IsNullOrEmpty(merchantCertPath) || string.IsNullOrEmpty(alipayCertPath) || string.IsNullOrEmpty(alipayCertPath))
  39. {
  40. throw new Exception("证书参数merchantCertPath、alipayCertPath或alipayRootCertPath设置不完整。");
  41. }
  42. this.RootCertContent = File.ReadAllText(alipayRootCertPath);
  43. this.RootCertSN = AntCertificationUtil.GetRootCertSN(RootCertContent);
  44. X509Certificate merchantCert = AntCertificationUtil.ParseCert(File.ReadAllText(merchantCertPath));
  45. this.MerchantCertSN = AntCertificationUtil.GetCertSN(merchantCert);
  46. X509Certificate alipayCert = AntCertificationUtil.ParseCert(File.ReadAllText(alipayCertPath));
  47. string alipayCertSN = AntCertificationUtil.GetCertSN(alipayCert);
  48. string alipayPublicKey = AntCertificationUtil.ExtractPemPublicKeyFromCert(alipayCert);
  49. CachedAlipayPublicKey[alipayCertSN] = alipayPublicKey;
  50. }
  51. public string GetAlipayPublicKey(string sn)
  52. {
  53. //如果没有指定sn,则默认取缓存中的第一个值
  54. if (string.IsNullOrEmpty(sn))
  55. {
  56. return CachedAlipayPublicKey.Values.FirstOrDefault();
  57. }
  58. if (CachedAlipayPublicKey.ContainsKey(sn))
  59. {
  60. return CachedAlipayPublicKey[sn];
  61. }
  62. else
  63. {
  64. //网关在支付宝公钥证书变更前,一定会确认通知到商户并在商户做出反馈后,才会更新该商户的支付宝公钥证书
  65. //TODO: 后续可以考虑加入自动升级支付宝公钥证书逻辑,注意并发更新冲突问题
  66. throw new Exception("支付宝公钥证书[" + sn + "]已过期,请重新下载最新支付宝公钥证书并替换原证书文件");
  67. }
  68. }
  69. }
  70. }