CertEnvironment.cs 3.2 KB

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