AntCertificationUtil.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. using System.Collections.Generic;
  2. using System;
  3. using Org.BouncyCastle.X509;
  4. using Org.BouncyCastle.Asn1.X509;
  5. using Org.BouncyCastle.Crypto;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Linq;
  9. namespace Alipay.EasySDK.Kernel.Util
  10. {
  11. /// <summary>
  12. /// 证书相关工具类
  13. /// </summary>
  14. public static class AntCertificationUtil
  15. {
  16. /// <summary>
  17. /// 提取根证书序列号
  18. /// </summary>
  19. /// <param name="rootCertContent">根证书文本</param>
  20. /// <returns>根证书序列号</returns>
  21. public static string GetRootCertSN(string rootCertContent)
  22. {
  23. string rootCertSN = "";
  24. try
  25. {
  26. List<X509Certificate> x509Certificates = ReadPemCertChain(rootCertContent);
  27. foreach (X509Certificate cert in x509Certificates)
  28. {
  29. //只提取与指定算法类型匹配的证书的序列号
  30. if (cert.SigAlgOid.StartsWith("1.2.840.113549.1.1", StringComparison.Ordinal))
  31. {
  32. string certSN = GetCertSN(cert);
  33. if (string.IsNullOrEmpty(rootCertSN))
  34. {
  35. rootCertSN = certSN;
  36. }
  37. else
  38. {
  39. rootCertSN = rootCertSN + "_" + certSN;
  40. }
  41. }
  42. }
  43. }
  44. catch (Exception ex)
  45. {
  46. throw new Exception("提取根证书序列号失败。" + ex.Message);
  47. }
  48. return rootCertSN;
  49. }
  50. /// <summary>
  51. /// 反序列化证书文本
  52. /// </summary>
  53. /// <param name="certContent">证书文本</param>
  54. /// <returns>X509Certificate证书对象</returns>
  55. public static X509Certificate ParseCert(string certContent)
  56. {
  57. return new X509CertificateParser().ReadCertificate(Encoding.UTF8.GetBytes(certContent));
  58. }
  59. /// <summary>
  60. /// 计算指定证书的序列号
  61. /// </summary>
  62. /// <param name="cert">证书</param>
  63. /// <returns>序列号</returns>
  64. public static string GetCertSN(X509Certificate cert)
  65. {
  66. string issuerDN = cert.IssuerDN.ToString();
  67. //提取出的证书的issuerDN本身是以CN开头的,则无需逆序,直接返回
  68. if (issuerDN.StartsWith("CN", StringComparison.Ordinal))
  69. {
  70. return CalculateMd5(issuerDN + cert.SerialNumber);
  71. }
  72. List<string> attributes = issuerDN.Split(',').ToList();
  73. attributes.Reverse();
  74. return CalculateMd5(string.Join(",", attributes.ToArray()) + cert.SerialNumber);
  75. }
  76. /// <summary>
  77. /// 校验证书链是否可信
  78. /// </summary>
  79. /// <param name="certContent">需要验证的目标证书或者证书链文本</param>
  80. /// <param name="rootCertContent">可信根证书列表文本</param>
  81. /// <returns>true:证书可信;false:证书不可信</returns>
  82. public static bool IsTrusted(string certContent, string rootCertContent)
  83. {
  84. List<X509Certificate> certs = ReadPemCertChain(certContent);
  85. List<X509Certificate> rootCerts = ReadPemCertChain(rootCertContent);
  86. return VerifyCertChain(certs, rootCerts);
  87. }
  88. /// <summary>
  89. /// 从证书链文本反序列化证书链集合
  90. /// </summary>
  91. /// <param name="cert">证书链文本</param>
  92. /// <returns>证书链集合</returns>
  93. private static List<X509Certificate> ReadPemCertChain(string cert)
  94. {
  95. System.Collections.ICollection collection = new X509CertificateParser().ReadCertificates(Encoding.UTF8.GetBytes(cert));
  96. List<X509Certificate> result = new List<X509Certificate>();
  97. foreach (var each in collection)
  98. {
  99. result.Add((X509Certificate)each);
  100. }
  101. return result;
  102. }
  103. /// <summary>
  104. /// 将证书链按照完整的签发顺序进行排序,排序后证书链为:[issuerA, subjectA]-[issuerA, subjectB]-[issuerB, subjectC]-[issuerC, subjectD]...
  105. /// </summary>
  106. /// <param name="certChain">未排序的证书链</param>
  107. /// <returns>true:排序成功;false:证书链不完整</returns>
  108. private static bool SortCertChain(List<X509Certificate> certChain)
  109. {
  110. //主题和证书的映射
  111. Dictionary<X509Name, X509Certificate> subject2CertMap = new Dictionary<X509Name, X509Certificate>();
  112. //签发者和证书的映射
  113. Dictionary<X509Name, X509Certificate> issuer2CertMap = new Dictionary<X509Name, X509Certificate>();
  114. //是否包含自签名证书
  115. bool hasSelfSignedCert = false;
  116. foreach (X509Certificate cert in certChain)
  117. {
  118. if (IsSelfSigned(cert))
  119. {
  120. if (hasSelfSignedCert)
  121. {
  122. //同一条证书链中只能有一个自签名证书
  123. return false;
  124. }
  125. hasSelfSignedCert = true;
  126. }
  127. subject2CertMap[cert.SubjectDN] = cert;
  128. issuer2CertMap[cert.IssuerDN] = cert;
  129. }
  130. List<X509Certificate> orderedCertChain = new List<X509Certificate>();
  131. X509Certificate current = certChain[0];
  132. AddressingUp(subject2CertMap, orderedCertChain, current);
  133. AddressingDown(issuer2CertMap, orderedCertChain, current);
  134. //说明证书链不完整
  135. if (certChain.Count != orderedCertChain.Count)
  136. {
  137. return false;
  138. }
  139. //用排序后的结果覆盖传入的证书链集合
  140. for (int i = 0; i < orderedCertChain.Count; i++)
  141. {
  142. certChain[i] = orderedCertChain[i];
  143. }
  144. return true;
  145. }
  146. private static bool IsSelfSigned(X509Certificate cert)
  147. {
  148. return cert.SubjectDN.Equivalent(cert.IssuerDN);
  149. }
  150. /// <summary>
  151. /// 向上构造证书链
  152. /// </summary>
  153. /// <param name="subject2CertMap">主题与证书的映射</param>
  154. /// <param name="orderedCertChain">储存排序后的证书链集合</param>
  155. /// <param name="current">当前需要插入排序后的证书链集合中的证书</param>
  156. private static void AddressingUp(Dictionary<X509Name, X509Certificate> subject2CertMap,
  157. List<X509Certificate> orderedCertChain, X509Certificate current)
  158. {
  159. orderedCertChain.Insert(0, current);
  160. if (IsSelfSigned(current))
  161. {
  162. return;
  163. }
  164. if (!subject2CertMap.ContainsKey(current.IssuerDN))
  165. {
  166. return;
  167. }
  168. X509Certificate issuer = subject2CertMap[current.IssuerDN];
  169. AddressingUp(subject2CertMap, orderedCertChain, issuer);
  170. }
  171. /// <summary>
  172. /// 向下构造证书链
  173. /// </summary>
  174. /// <param name="issuer2CertMap">签发者和证书的映射</param>
  175. /// <param name="certChain">储存排序后的证书链集合</param>
  176. /// <param name="current">当前需要插入排序后的证书链集合中的证书</param>
  177. private static void AddressingDown(Dictionary<X509Name, X509Certificate> issuer2CertMap,
  178. List<X509Certificate> certChain, X509Certificate current)
  179. {
  180. if (!issuer2CertMap.ContainsKey(current.SubjectDN))
  181. {
  182. return;
  183. }
  184. X509Certificate subject = issuer2CertMap[current.SubjectDN];
  185. if (IsSelfSigned(subject))
  186. {
  187. return;
  188. }
  189. certChain.Add(subject);
  190. AddressingDown(issuer2CertMap, certChain, subject);
  191. }
  192. /// <summary>
  193. /// 验证证书是否是信任证书库中的证书签发的
  194. /// </summary>
  195. /// <param name="cert">待验证证书</param>
  196. /// <param name="rootCerts">可信根证书列表</param>
  197. /// <returns>true:验证通过;false:验证不通过</returns>
  198. private static bool VerifyCert(X509Certificate cert, List<X509Certificate> rootCerts)
  199. {
  200. if (!cert.IsValidNow)
  201. {
  202. return false;
  203. }
  204. Dictionary<X509Name, X509Certificate> subject2CertMap = new Dictionary<X509Name, X509Certificate>();
  205. foreach (X509Certificate root in rootCerts)
  206. {
  207. subject2CertMap[root.SubjectDN] = root;
  208. }
  209. X509Name issuerDN = cert.IssuerDN;
  210. if (!subject2CertMap.ContainsKey(issuerDN))
  211. {
  212. return false;
  213. }
  214. X509Certificate issuer = subject2CertMap[issuerDN];
  215. try
  216. {
  217. AsymmetricKeyParameter publicKey = issuer.GetPublicKey();
  218. cert.Verify(publicKey);
  219. }
  220. catch (Exception ex)
  221. {
  222. Console.WriteLine("证书验证出现异常。" + ex.Message);
  223. return false;
  224. }
  225. return true;
  226. }
  227. /// <summary>
  228. /// 验证证书列表
  229. /// </summary>
  230. /// <param name="certs">待验证的证书列表</param>
  231. /// <param name="rootCerts">可信根证书列表</param>
  232. /// <returns>true:验证通过;false:验证不通过</returns>
  233. private static bool VerifyCertChain(List<X509Certificate> certs, List<X509Certificate> rootCerts)
  234. {
  235. //证书列表排序,形成排序后的证书链
  236. bool sorted = SortCertChain(certs);
  237. if (!sorted)
  238. {
  239. //不是完整的证书链
  240. return false;
  241. }
  242. //先验证第一个证书是不是信任库中证书签发的
  243. X509Certificate previous = certs[0];
  244. bool firstOK = VerifyCert(previous, rootCerts);
  245. if (!firstOK || certs.Count == 1)
  246. {
  247. return firstOK;
  248. }
  249. //验证证书链
  250. for (int i = 1; i < certs.Count; i++)
  251. {
  252. try
  253. {
  254. X509Certificate cert = certs[i];
  255. if (!cert.IsValidNow)
  256. {
  257. return false;
  258. }
  259. //用上级证书的公钥验证本证书是否是上级证书签发的
  260. cert.Verify(previous.GetPublicKey());
  261. previous = cert;
  262. }
  263. catch (Exception ex)
  264. {
  265. //证书链验证失败
  266. Console.WriteLine("证书链验证失败。" + ex.Message);
  267. return false;
  268. }
  269. }
  270. return true;
  271. }
  272. private static string CalculateMd5(string input)
  273. {
  274. using (MD5 md5 = new MD5CryptoServiceProvider())
  275. {
  276. string result = "";
  277. byte[] bytes = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(input));
  278. for (int i = 0; i < bytes.Length; i++)
  279. {
  280. result += bytes[i].ToString("x2");
  281. }
  282. return result;
  283. }
  284. }
  285. /// <summary>
  286. /// 从证书中提取公钥并转换为PEM编码
  287. /// </summary>
  288. /// <param name="input">证书</param>
  289. /// <returns>PEM编码公钥</returns>
  290. public static string ExtractPemPublicKeyFromCert(X509Certificate input)
  291. {
  292. SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(input.GetPublicKey());
  293. return Convert.ToBase64String(subjectPublicKeyInfo.GetDerEncoded());
  294. }
  295. }
  296. }