RsaPem.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. using Masuit.Tools.Systems;
  2. using System;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Numerics;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. namespace Masuit.Tools.Security;
  10. /// <summary>
  11. /// RSA PEM格式密钥对的解析和导出
  12. /// </summary>
  13. internal class RsaPem
  14. {
  15. /// <summary>
  16. /// modulus 模数n,公钥、私钥都有
  17. /// </summary>
  18. public byte[] KeyModulus;
  19. /// <summary>
  20. /// publicExponent 公钥指数e,公钥、私钥都有
  21. /// </summary>
  22. public byte[] KeyExponent;
  23. /// <summary>
  24. /// privateExponent 私钥指数d,只有私钥的时候才有
  25. /// </summary>
  26. public byte[] KeyD;
  27. //以下参数只有私钥才有 https://docs.microsoft.com/zh-cn/dotnet/api/system.security.cryptography.rsaparameters?redirectedfrom=MSDN&view=netframework-4.8
  28. /// <summary>
  29. /// prime1
  30. /// </summary>
  31. public byte[] ValP;
  32. /// <summary>
  33. /// prime2
  34. /// </summary>
  35. public byte[] ValQ;
  36. /// <summary>
  37. /// exponent1
  38. /// </summary>
  39. public byte[] ValDp;
  40. /// <summary>
  41. /// exponent2
  42. /// </summary>
  43. public byte[] ValDq;
  44. /// <summary>
  45. /// coefficient
  46. /// </summary>
  47. public byte[] ValInverseQ;
  48. private RsaPem()
  49. {
  50. }
  51. /// <summary>
  52. /// 通过RSA中的公钥和私钥构造一个PEM,如果convertToPublic含私钥的RSA将只读取公钥,仅含公钥的RSA不受影响
  53. /// </summary>
  54. public RsaPem(RSACryptoServiceProvider rsa, bool convertToPublic = false)
  55. {
  56. var isPublic = convertToPublic || rsa.PublicOnly;
  57. var param = rsa.ExportParameters(!isPublic);
  58. KeyModulus = param.Modulus;
  59. KeyExponent = param.Exponent;
  60. if (!isPublic)
  61. {
  62. KeyD = param.D;
  63. ValP = param.P;
  64. ValQ = param.Q;
  65. ValDp = param.DP;
  66. ValDq = param.DQ;
  67. ValInverseQ = param.InverseQ;
  68. }
  69. }
  70. /// <summary>
  71. /// 通过全量的PEM字段数据构造一个PEM,除了模数modulus和公钥指数exponent必须提供外,其他私钥指数信息要么全部提供,要么全部不提供(导出的PEM就只包含公钥)
  72. /// 注意:所有参数首字节如果是0,必须先去掉
  73. /// </summary>
  74. public RsaPem(byte[] modulus, byte[] exponent, byte[] d, byte[] p, byte[] q, byte[] dp, byte[] dq, byte[] inverseQ)
  75. {
  76. KeyModulus = modulus;
  77. KeyExponent = exponent;
  78. KeyD = d;
  79. ValP = p;
  80. ValQ = q;
  81. ValDp = dp;
  82. ValDq = dq;
  83. ValInverseQ = inverseQ;
  84. }
  85. /// <summary>
  86. /// 通过公钥指数和私钥指数构造一个PEM,会反推计算出P、Q但和原始生成密钥的P、Q极小可能相同
  87. /// 注意:所有参数首字节如果是0,必须先去掉
  88. /// 出错将会抛出异常
  89. /// </summary>
  90. /// <param name="modulus">必须提供模数</param>
  91. /// <param name="exponent">必须提供公钥指数</param>
  92. /// <param name="dOrNull">私钥指数可以不提供,导出的PEM就只包含公钥</param>
  93. public RsaPem(byte[] modulus, byte[] exponent, byte[] dOrNull)
  94. {
  95. KeyModulus = modulus; //modulus
  96. KeyExponent = exponent; //publicExponent
  97. if (dOrNull != null)
  98. {
  99. KeyD = dOrNull; //privateExponent
  100. //反推P、Q
  101. BigInteger n = BigX(modulus);
  102. BigInteger e = BigX(exponent);
  103. BigInteger d = BigX(dOrNull);
  104. BigInteger p = FindFactor(e, d, n);
  105. BigInteger q = n / p;
  106. if (p.CompareTo(q) > 0)
  107. {
  108. (p, q) = (q, p);
  109. }
  110. BigInteger exp1 = d % (p - BigInteger.One);
  111. BigInteger exp2 = d % (q - BigInteger.One);
  112. BigInteger coeff = BigInteger.ModPow(q, p - 2, p);
  113. ValP = BigB(p); //prime1
  114. ValQ = BigB(q); //prime2
  115. ValDp = BigB(exp1); //exponent1
  116. ValDq = BigB(exp2); //exponent2
  117. ValInverseQ = BigB(coeff); //coefficient
  118. }
  119. }
  120. /// <summary>
  121. /// 密钥位数
  122. /// </summary>
  123. public int KeySize => KeyModulus.Length * 8;
  124. /// <summary>
  125. /// 是否包含私钥
  126. /// </summary>
  127. public bool HasPrivate => KeyD != null;
  128. /// <summary>
  129. /// 将PEM中的公钥私钥转成RSA对象,如果未提供私钥,RSA中就只包含公钥
  130. /// </summary>
  131. public RSACryptoServiceProvider GetRSA()
  132. {
  133. //var rsaParams = System.Security.Cryptography.RSA.Create();
  134. //rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;
  135. var rsa = new RSACryptoServiceProvider();
  136. var param = new RSAParameters
  137. {
  138. Modulus = KeyModulus,
  139. Exponent = KeyExponent
  140. };
  141. if (KeyD != null)
  142. {
  143. param.D = KeyD;
  144. param.P = ValP;
  145. param.Q = ValQ;
  146. param.DP = ValDp;
  147. param.DQ = ValDq;
  148. param.InverseQ = ValInverseQ;
  149. }
  150. rsa.ImportParameters(param);
  151. return rsa;
  152. }
  153. /// <summary>
  154. /// 转成正整数,如果是负数,需要加前导0转成正整数
  155. /// </summary>
  156. public static BigInteger BigX(byte[] bigb)
  157. {
  158. if (bigb[0] > 127)
  159. {
  160. byte[] c = new byte[bigb.Length + 1];
  161. Array.Copy(bigb, 0, c, 1, bigb.Length);
  162. bigb = c;
  163. }
  164. bigb.Reverse();
  165. return new BigInteger(bigb);
  166. }
  167. /// <summary>
  168. /// BigInt导出byte整数首字节>0x7F的会加0前导,保证正整数,因此需要去掉0
  169. /// </summary>
  170. public static byte[] BigB(BigInteger bigx)
  171. {
  172. var bytes = bigx.ToByteArray();
  173. bytes.Reverse();
  174. if (bytes[0] == 0)
  175. {
  176. byte[] c = new byte[bytes.Length - 1];
  177. Array.Copy(bytes, 1, c, 0, c.Length);
  178. bytes = c;
  179. }
  180. return bytes;
  181. }
  182. /// <summary>
  183. /// 由n e d 反推 P Q
  184. /// </summary>
  185. private static BigInteger FindFactor(BigInteger e, BigInteger d, BigInteger n)
  186. {
  187. BigInteger edMinus1 = e * d - BigInteger.One;
  188. int s = -1;
  189. if (edMinus1 != BigInteger.Zero)
  190. {
  191. s = (int)(BigInteger.Log(edMinus1 & -edMinus1) / BigInteger.Log(2));
  192. }
  193. BigInteger t = edMinus1 >> s;
  194. long now = DateTime.Now.Ticks;
  195. for (int aInt = 2; ; aInt++)
  196. {
  197. if (aInt % 10 == 0 && DateTime.Now.Ticks - now > 3000 * 10000)
  198. {
  199. throw new Exception("推算RSA.P超时"); //测试最多循环2次,1024位的速度很快 8ms
  200. }
  201. BigInteger aPow = BigInteger.ModPow(new BigInteger(aInt), t, n);
  202. for (int i = 1; i <= s; i++)
  203. {
  204. if (aPow == BigInteger.One)
  205. {
  206. break;
  207. }
  208. if (aPow == n - BigInteger.One)
  209. {
  210. break;
  211. }
  212. BigInteger aPowSquared = aPow * aPow % n;
  213. if (aPowSquared == BigInteger.One)
  214. {
  215. return BigInteger.GreatestCommonDivisor(aPow - BigInteger.One, n);
  216. }
  217. aPow = aPowSquared;
  218. }
  219. }
  220. }
  221. /// <summary>
  222. /// 用PEM格式密钥对创建RSA,支持PKCS#1、PKCS#8格式的PEM
  223. /// 出错将会抛出异常
  224. /// </summary>
  225. public static RsaPem FromPEM(string pem)
  226. {
  227. RsaPem param = new RsaPem();
  228. var arr = pem.Split('\n');
  229. var base64 = arr.Skip(1).Take(arr.Length - 2).Join("\n");
  230. byte[] data;
  231. try
  232. {
  233. data = Convert.FromBase64String(base64);
  234. }
  235. catch
  236. {
  237. throw new Exception("PEM内容无效");
  238. }
  239. var idx = 0;
  240. //读取长度
  241. Func<byte, int> readLen = (first) =>
  242. {
  243. if (data[idx] == first)
  244. {
  245. idx++;
  246. if (data[idx] == 0x81)
  247. {
  248. idx++;
  249. return data[idx++];
  250. }
  251. if (data[idx] == 0x82)
  252. {
  253. idx++;
  254. return ((data[idx++]) << 8) + data[idx++];
  255. }
  256. if (data[idx] < 0x80)
  257. {
  258. return data[idx++];
  259. }
  260. }
  261. throw new Exception("PEM未能提取到数据");
  262. };
  263. //读取块数据
  264. Func<byte[]> readBlock = () =>
  265. {
  266. var len = readLen(0x02);
  267. if (data[idx] == 0x00)
  268. {
  269. idx++;
  270. len--;
  271. }
  272. var val = new byte[len];
  273. for (var i = 0; i < len; i++)
  274. {
  275. val[i] = data[idx + i];
  276. }
  277. idx += len;
  278. return val;
  279. };
  280. //比较data从idx位置开始是否是byts内容
  281. Func<byte[], bool> eq = byts =>
  282. {
  283. for (var i = 0; i < byts.Length; i++, idx++)
  284. {
  285. if (idx >= data.Length)
  286. {
  287. return false;
  288. }
  289. if (byts[i] != data[idx])
  290. {
  291. return false;
  292. }
  293. }
  294. return true;
  295. };
  296. if (pem.Contains("PUBLIC KEY"))
  297. {
  298. //使用公钥
  299. //读取数据总长度
  300. readLen(0x30);
  301. //看看有没有oid
  302. var idx2 = idx;
  303. if (eq(SeqOid))
  304. {
  305. //读取1长度
  306. readLen(0x03);
  307. idx++; //跳过0x00
  308. //读取2长度
  309. readLen(0x30);
  310. }
  311. else
  312. {
  313. idx = idx2;
  314. }
  315. //Modulus
  316. param.KeyModulus = readBlock();
  317. //Exponent
  318. param.KeyExponent = readBlock();
  319. }
  320. else if (pem.Contains("PRIVATE KEY"))
  321. {
  322. //使用私钥
  323. //读取数据总长度
  324. readLen(0x30);
  325. //读取版本号
  326. if (!eq(Ver))
  327. {
  328. throw new Exception("PEM未知版本");
  329. }
  330. //检测PKCS8
  331. var idx2 = idx;
  332. if (eq(SeqOid))
  333. {
  334. //读取1长度
  335. readLen(0x04);
  336. //读取2长度
  337. readLen(0x30);
  338. //读取版本号
  339. if (!eq(Ver))
  340. {
  341. throw new Exception("PEM版本无效");
  342. }
  343. }
  344. else
  345. {
  346. idx = idx2;
  347. }
  348. //读取数据
  349. param.KeyModulus = readBlock();
  350. param.KeyExponent = readBlock();
  351. param.KeyD = readBlock();
  352. param.ValP = readBlock();
  353. param.ValQ = readBlock();
  354. param.ValDp = readBlock();
  355. param.ValDq = readBlock();
  356. param.ValInverseQ = readBlock();
  357. }
  358. else
  359. {
  360. throw new Exception("pem需要BEGIN END标头");
  361. }
  362. return param;
  363. }
  364. private static readonly byte[] SeqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
  365. private static readonly byte[] Ver = { 0x02, 0x01, 0x00 };
  366. /// <summary>
  367. /// 将RSA中的密钥对转换成PEM格式,usePKCS8=false时返回PKCS#1格式,否则返回PKCS#8格式,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
  368. /// </summary>
  369. public string ToPEM(bool convertToPublic, bool usePKCS8)
  370. {
  371. var ms = new PooledMemoryStream();
  372. //写入一个长度字节码
  373. Action<int> writeLenByte = len =>
  374. {
  375. if (len < 0x80)
  376. {
  377. ms.WriteByte((byte)len);
  378. }
  379. else if (len <= 0xff)
  380. {
  381. ms.WriteByte(0x81);
  382. ms.WriteByte((byte)len);
  383. }
  384. else
  385. {
  386. ms.WriteByte(0x82);
  387. ms.WriteByte((byte)(len >> 8 & 0xff));
  388. ms.WriteByte((byte)(len & 0xff));
  389. }
  390. };
  391. //写入一块数据
  392. Action<byte[]> writeBlock = byts =>
  393. {
  394. var addZero = (byts[0] >> 4) >= 0x8;
  395. ms.WriteByte(0x02);
  396. var len = byts.Length + (addZero ? 1 : 0);
  397. writeLenByte(len);
  398. if (addZero)
  399. {
  400. ms.WriteByte(0x00);
  401. }
  402. ms.Write(byts, 0, byts.Length);
  403. };
  404. //根据后续内容长度写入长度数据
  405. Func<int, byte[], byte[]> writeLen = (index, byts) =>
  406. {
  407. var len = byts.Length - index;
  408. ms.SetLength(0);
  409. ms.Write(byts, 0, index);
  410. writeLenByte(len);
  411. ms.Write(byts, index, len);
  412. return ms.ToArray();
  413. };
  414. Action<Stream, byte[]> writeAll = (stream, byts) =>
  415. {
  416. stream.Write(byts, 0, byts.Length);
  417. };
  418. Func<string, int, string> TextBreak = (text, line) =>
  419. {
  420. var idx = 0;
  421. var len = text.Length;
  422. var str = new StringBuilder();
  423. while (idx < len)
  424. {
  425. if (idx > 0)
  426. {
  427. str.Append('\n');
  428. }
  429. str.Append(idx + line >= len ? text.Substring(idx) : text.Substring(idx, line));
  430. idx += line;
  431. }
  432. return str.ToString();
  433. };
  434. if (KeyD == null || convertToPublic)
  435. {
  436. //生成公钥
  437. //写入总字节数,不含本段长度,额外需要24字节的头,后续计算好填入
  438. ms.WriteByte(0x30);
  439. var index1 = (int)ms.Length;
  440. //固定内容
  441. writeAll(ms, SeqOid);
  442. //从0x00开始的后续长度
  443. ms.WriteByte(0x03);
  444. var index2 = (int)ms.Length;
  445. ms.WriteByte(0x00);
  446. //后续内容长度
  447. ms.WriteByte(0x30);
  448. var index3 = (int)ms.Length;
  449. //写入Modulus
  450. writeBlock(KeyModulus);
  451. //写入Exponent
  452. writeBlock(KeyExponent);
  453. //计算空缺的长度
  454. var bytes = ms.ToArray();
  455. bytes = writeLen(index3, bytes);
  456. bytes = writeLen(index2, bytes);
  457. bytes = writeLen(index1, bytes);
  458. return "-----BEGIN PUBLIC KEY-----\n" + TextBreak(Convert.ToBase64String(bytes), 64) + "\n-----END PUBLIC KEY-----";
  459. }
  460. else
  461. {
  462. /****生成私钥****/
  463. //写入总字节数,后续写入
  464. ms.WriteByte(0x30);
  465. int index1 = (int)ms.Length;
  466. //写入版本号
  467. writeAll(ms, Ver);
  468. //PKCS8 多一段数据
  469. int index2 = -1, index3 = -1;
  470. if (usePKCS8)
  471. {
  472. //固定内容
  473. writeAll(ms, SeqOid);
  474. //后续内容长度
  475. ms.WriteByte(0x04);
  476. index2 = (int)ms.Length;
  477. //后续内容长度
  478. ms.WriteByte(0x30);
  479. index3 = (int)ms.Length;
  480. //写入版本号
  481. writeAll(ms, Ver);
  482. }
  483. //写入数据
  484. writeBlock(KeyModulus);
  485. writeBlock(KeyExponent);
  486. writeBlock(KeyD);
  487. writeBlock(ValP);
  488. writeBlock(ValQ);
  489. writeBlock(ValDp);
  490. writeBlock(ValDq);
  491. writeBlock(ValInverseQ);
  492. //计算空缺的长度
  493. var byts = ms.ToArray();
  494. if (index2 != -1)
  495. {
  496. byts = writeLen(index3, byts);
  497. byts = writeLen(index2, byts);
  498. }
  499. byts = writeLen(index1, byts);
  500. var flag = " PRIVATE KEY";
  501. if (!usePKCS8)
  502. {
  503. flag = " RSA" + flag;
  504. }
  505. return "-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(byts), 64) + "\n-----END" + flag + "-----";
  506. }
  507. }
  508. /// <summary>
  509. /// 将XML格式密钥转成PEM,支持公钥xml、私钥xml
  510. /// 出错将会抛出异常
  511. /// </summary>
  512. public static RsaPem FromXML(string xml)
  513. {
  514. var rtv = new RsaPem();
  515. var xmlM = XmlExp.Match(xml);
  516. if (!xmlM.Success)
  517. {
  518. throw new Exception("XML内容不符合要求");
  519. }
  520. var tagM = XmlTagExp.Match(xmlM.Groups[1].Value);
  521. while (tagM.Success)
  522. {
  523. string tag = tagM.Groups[1].Value;
  524. string b64 = tagM.Groups[2].Value;
  525. byte[] val = Convert.FromBase64String(b64);
  526. switch (tag)
  527. {
  528. case "Modulus":
  529. rtv.KeyModulus = val;
  530. break;
  531. case "Exponent":
  532. rtv.KeyExponent = val;
  533. break;
  534. case "D":
  535. rtv.KeyD = val;
  536. break;
  537. case "P":
  538. rtv.ValP = val;
  539. break;
  540. case "Q":
  541. rtv.ValQ = val;
  542. break;
  543. case "DP":
  544. rtv.ValDp = val;
  545. break;
  546. case "DQ":
  547. rtv.ValDq = val;
  548. break;
  549. case "InverseQ":
  550. rtv.ValInverseQ = val;
  551. break;
  552. }
  553. tagM = tagM.NextMatch();
  554. }
  555. if (rtv.KeyModulus == null || rtv.KeyExponent == null)
  556. {
  557. throw new Exception("XML公钥丢失");
  558. }
  559. if (rtv.KeyD != null)
  560. {
  561. if (rtv.ValP == null || rtv.ValQ == null || rtv.ValDp == null || rtv.ValDq == null || rtv.ValInverseQ == null)
  562. {
  563. return new RsaPem(rtv.KeyModulus, rtv.KeyExponent, rtv.KeyD);
  564. }
  565. }
  566. return rtv;
  567. }
  568. private static readonly Regex XmlExp = new(@"\s*<RSAKeyValue>([<>\/\+=\w\s]+)</RSAKeyValue>\s*");
  569. private static readonly Regex XmlTagExp = new(@"<(.+?)>\s*([^<]+?)\s*</");
  570. /// <summary>
  571. /// 将RSA中的密钥对转换成XML格式
  572. /// ,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
  573. /// </summary>
  574. public string ToXML(bool convertToPublic)
  575. {
  576. StringBuilder str = new StringBuilder();
  577. str.Append("<RSAKeyValue>");
  578. str.Append("<Modulus>" + Convert.ToBase64String(KeyModulus) + "</Modulus>");
  579. str.Append("<Exponent>" + Convert.ToBase64String(KeyExponent) + "</Exponent>");
  580. if (KeyD != null && !convertToPublic)
  581. {
  582. /****生成私钥****/
  583. str.Append("<P>" + Convert.ToBase64String(ValP) + "</P>");
  584. str.Append("<Q>" + Convert.ToBase64String(ValQ) + "</Q>");
  585. str.Append("<DP>" + Convert.ToBase64String(ValDp) + "</DP>");
  586. str.Append("<DQ>" + Convert.ToBase64String(ValDq) + "</DQ>");
  587. str.Append("<InverseQ>" + Convert.ToBase64String(ValInverseQ) + "</InverseQ>");
  588. str.Append("<D>" + Convert.ToBase64String(KeyD) + "</D>");
  589. }
  590. str.Append("</RSAKeyValue>");
  591. return str.ToString();
  592. }
  593. }