RsaPem.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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. return new BigInteger(bigb.Reverse().ToArray()); //C#的二进制是反的
  165. }
  166. /// <summary>
  167. /// BigInt导出byte整数首字节>0x7F的会加0前导,保证正整数,因此需要去掉0
  168. /// </summary>
  169. public static byte[] BigB(BigInteger bigx)
  170. {
  171. byte[] val = bigx.ToByteArray().Reverse().ToArray(); //C#的二进制是反的
  172. if (val[0] == 0)
  173. {
  174. byte[] c = new byte[val.Length - 1];
  175. Array.Copy(val, 1, c, 0, c.Length);
  176. val = c;
  177. }
  178. return val;
  179. }
  180. /// <summary>
  181. /// 由n e d 反推 P Q
  182. /// </summary>
  183. private static BigInteger FindFactor(BigInteger e, BigInteger d, BigInteger n)
  184. {
  185. BigInteger edMinus1 = e * d - BigInteger.One;
  186. int s = -1;
  187. if (edMinus1 != BigInteger.Zero)
  188. {
  189. s = (int)(BigInteger.Log(edMinus1 & -edMinus1) / BigInteger.Log(2));
  190. }
  191. BigInteger t = edMinus1 >> s;
  192. long now = DateTime.Now.Ticks;
  193. for (int aInt = 2; ; aInt++)
  194. {
  195. if (aInt % 10 == 0 && DateTime.Now.Ticks - now > 3000 * 10000)
  196. {
  197. throw new Exception("推算RSA.P超时"); //测试最多循环2次,1024位的速度很快 8ms
  198. }
  199. BigInteger aPow = BigInteger.ModPow(new BigInteger(aInt), t, n);
  200. for (int i = 1; i <= s; i++)
  201. {
  202. if (aPow == BigInteger.One)
  203. {
  204. break;
  205. }
  206. if (aPow == n - BigInteger.One)
  207. {
  208. break;
  209. }
  210. BigInteger aPowSquared = aPow * aPow % n;
  211. if (aPowSquared == BigInteger.One)
  212. {
  213. return BigInteger.GreatestCommonDivisor(aPow - BigInteger.One, n);
  214. }
  215. aPow = aPowSquared;
  216. }
  217. }
  218. }
  219. /// <summary>
  220. /// 用PEM格式密钥对创建RSA,支持PKCS#1、PKCS#8格式的PEM
  221. /// 出错将会抛出异常
  222. /// </summary>
  223. public static RsaPem FromPEM(string pem)
  224. {
  225. RsaPem param = new RsaPem();
  226. var arr = pem.Split('\n');
  227. var base64 = arr.Skip(1).Take(arr.Length - 2).Join("\n");
  228. byte[] data;
  229. try
  230. {
  231. data = Convert.FromBase64String(base64);
  232. }
  233. catch
  234. {
  235. throw new Exception("PEM内容无效");
  236. }
  237. var idx = 0;
  238. //读取长度
  239. Func<byte, int> readLen = (first) =>
  240. {
  241. if (data[idx] == first)
  242. {
  243. idx++;
  244. if (data[idx] == 0x81)
  245. {
  246. idx++;
  247. return data[idx++];
  248. }
  249. if (data[idx] == 0x82)
  250. {
  251. idx++;
  252. return ((data[idx++]) << 8) + data[idx++];
  253. }
  254. if (data[idx] < 0x80)
  255. {
  256. return data[idx++];
  257. }
  258. }
  259. throw new Exception("PEM未能提取到数据");
  260. };
  261. //读取块数据
  262. Func<byte[]> readBlock = () =>
  263. {
  264. var len = readLen(0x02);
  265. if (data[idx] == 0x00)
  266. {
  267. idx++;
  268. len--;
  269. }
  270. var val = new byte[len];
  271. for (var i = 0; i < len; i++)
  272. {
  273. val[i] = data[idx + i];
  274. }
  275. idx += len;
  276. return val;
  277. };
  278. //比较data从idx位置开始是否是byts内容
  279. Func<byte[], bool> eq = byts =>
  280. {
  281. for (var i = 0; i < byts.Length; i++, idx++)
  282. {
  283. if (idx >= data.Length)
  284. {
  285. return false;
  286. }
  287. if (byts[i] != data[idx])
  288. {
  289. return false;
  290. }
  291. }
  292. return true;
  293. };
  294. if (pem.Contains("PUBLIC KEY"))
  295. {
  296. //使用公钥
  297. //读取数据总长度
  298. readLen(0x30);
  299. //看看有没有oid
  300. var idx2 = idx;
  301. if (eq(SeqOid))
  302. {
  303. //读取1长度
  304. readLen(0x03);
  305. idx++; //跳过0x00
  306. //读取2长度
  307. readLen(0x30);
  308. }
  309. else
  310. {
  311. idx = idx2;
  312. }
  313. //Modulus
  314. param.KeyModulus = readBlock();
  315. //Exponent
  316. param.KeyExponent = readBlock();
  317. }
  318. else if (pem.Contains("PRIVATE KEY"))
  319. {
  320. //使用私钥
  321. //读取数据总长度
  322. readLen(0x30);
  323. //读取版本号
  324. if (!eq(Ver))
  325. {
  326. throw new Exception("PEM未知版本");
  327. }
  328. //检测PKCS8
  329. var idx2 = idx;
  330. if (eq(SeqOid))
  331. {
  332. //读取1长度
  333. readLen(0x04);
  334. //读取2长度
  335. readLen(0x30);
  336. //读取版本号
  337. if (!eq(Ver))
  338. {
  339. throw new Exception("PEM版本无效");
  340. }
  341. }
  342. else
  343. {
  344. idx = idx2;
  345. }
  346. //读取数据
  347. param.KeyModulus = readBlock();
  348. param.KeyExponent = readBlock();
  349. param.KeyD = readBlock();
  350. param.ValP = readBlock();
  351. param.ValQ = readBlock();
  352. param.ValDp = readBlock();
  353. param.ValDq = readBlock();
  354. param.ValInverseQ = readBlock();
  355. }
  356. else
  357. {
  358. throw new Exception("pem需要BEGIN END标头");
  359. }
  360. return param;
  361. }
  362. private static readonly byte[] SeqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
  363. private static readonly byte[] Ver = { 0x02, 0x01, 0x00 };
  364. /// <summary>
  365. /// 将RSA中的密钥对转换成PEM格式,usePKCS8=false时返回PKCS#1格式,否则返回PKCS#8格式,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
  366. /// </summary>
  367. public string ToPEM(bool convertToPublic, bool usePKCS8)
  368. {
  369. var ms = new PooledMemoryStream();
  370. //写入一个长度字节码
  371. Action<int> writeLenByte = len =>
  372. {
  373. if (len < 0x80)
  374. {
  375. ms.WriteByte((byte)len);
  376. }
  377. else if (len <= 0xff)
  378. {
  379. ms.WriteByte(0x81);
  380. ms.WriteByte((byte)len);
  381. }
  382. else
  383. {
  384. ms.WriteByte(0x82);
  385. ms.WriteByte((byte)(len >> 8 & 0xff));
  386. ms.WriteByte((byte)(len & 0xff));
  387. }
  388. };
  389. //写入一块数据
  390. Action<byte[]> writeBlock = byts =>
  391. {
  392. var addZero = (byts[0] >> 4) >= 0x8;
  393. ms.WriteByte(0x02);
  394. var len = byts.Length + (addZero ? 1 : 0);
  395. writeLenByte(len);
  396. if (addZero)
  397. {
  398. ms.WriteByte(0x00);
  399. }
  400. ms.Write(byts, 0, byts.Length);
  401. };
  402. //根据后续内容长度写入长度数据
  403. Func<int, byte[], byte[]> writeLen = (index, byts) =>
  404. {
  405. var len = byts.Length - index;
  406. ms.SetLength(0);
  407. ms.Write(byts, 0, index);
  408. writeLenByte(len);
  409. ms.Write(byts, index, len);
  410. return ms.ToArray();
  411. };
  412. Action<Stream, byte[]> writeAll = (stream, byts) =>
  413. {
  414. stream.Write(byts, 0, byts.Length);
  415. };
  416. Func<string, int, string> TextBreak = (text, line) =>
  417. {
  418. var idx = 0;
  419. var len = text.Length;
  420. var str = new StringBuilder();
  421. while (idx < len)
  422. {
  423. if (idx > 0)
  424. {
  425. str.Append('\n');
  426. }
  427. str.Append(idx + line >= len ? text.Substring(idx) : text.Substring(idx, line));
  428. idx += line;
  429. }
  430. return str.ToString();
  431. };
  432. if (KeyD == null || convertToPublic)
  433. {
  434. //生成公钥
  435. //写入总字节数,不含本段长度,额外需要24字节的头,后续计算好填入
  436. ms.WriteByte(0x30);
  437. var index1 = (int)ms.Length;
  438. //固定内容
  439. writeAll(ms, SeqOid);
  440. //从0x00开始的后续长度
  441. ms.WriteByte(0x03);
  442. var index2 = (int)ms.Length;
  443. ms.WriteByte(0x00);
  444. //后续内容长度
  445. ms.WriteByte(0x30);
  446. var index3 = (int)ms.Length;
  447. //写入Modulus
  448. writeBlock(KeyModulus);
  449. //写入Exponent
  450. writeBlock(KeyExponent);
  451. //计算空缺的长度
  452. var bytes = ms.ToArray();
  453. bytes = writeLen(index3, bytes);
  454. bytes = writeLen(index2, bytes);
  455. bytes = writeLen(index1, bytes);
  456. return "-----BEGIN PUBLIC KEY-----\n" + TextBreak(Convert.ToBase64String(bytes), 64) + "\n-----END PUBLIC KEY-----";
  457. }
  458. else
  459. {
  460. /****生成私钥****/
  461. //写入总字节数,后续写入
  462. ms.WriteByte(0x30);
  463. int index1 = (int)ms.Length;
  464. //写入版本号
  465. writeAll(ms, Ver);
  466. //PKCS8 多一段数据
  467. int index2 = -1, index3 = -1;
  468. if (usePKCS8)
  469. {
  470. //固定内容
  471. writeAll(ms, SeqOid);
  472. //后续内容长度
  473. ms.WriteByte(0x04);
  474. index2 = (int)ms.Length;
  475. //后续内容长度
  476. ms.WriteByte(0x30);
  477. index3 = (int)ms.Length;
  478. //写入版本号
  479. writeAll(ms, Ver);
  480. }
  481. //写入数据
  482. writeBlock(KeyModulus);
  483. writeBlock(KeyExponent);
  484. writeBlock(KeyD);
  485. writeBlock(ValP);
  486. writeBlock(ValQ);
  487. writeBlock(ValDp);
  488. writeBlock(ValDq);
  489. writeBlock(ValInverseQ);
  490. //计算空缺的长度
  491. var byts = ms.ToArray();
  492. if (index2 != -1)
  493. {
  494. byts = writeLen(index3, byts);
  495. byts = writeLen(index2, byts);
  496. }
  497. byts = writeLen(index1, byts);
  498. var flag = " PRIVATE KEY";
  499. if (!usePKCS8)
  500. {
  501. flag = " RSA" + flag;
  502. }
  503. return "-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(byts), 64) + "\n-----END" + flag + "-----";
  504. }
  505. }
  506. /// <summary>
  507. /// 将XML格式密钥转成PEM,支持公钥xml、私钥xml
  508. /// 出错将会抛出异常
  509. /// </summary>
  510. public static RsaPem FromXML(string xml)
  511. {
  512. var rtv = new RsaPem();
  513. var xmlM = XmlExp.Match(xml);
  514. if (!xmlM.Success)
  515. {
  516. throw new Exception("XML内容不符合要求");
  517. }
  518. var tagM = XmlTagExp.Match(xmlM.Groups[1].Value);
  519. while (tagM.Success)
  520. {
  521. string tag = tagM.Groups[1].Value;
  522. string b64 = tagM.Groups[2].Value;
  523. byte[] val = Convert.FromBase64String(b64);
  524. switch (tag)
  525. {
  526. case "Modulus":
  527. rtv.KeyModulus = val;
  528. break;
  529. case "Exponent":
  530. rtv.KeyExponent = val;
  531. break;
  532. case "D":
  533. rtv.KeyD = val;
  534. break;
  535. case "P":
  536. rtv.ValP = val;
  537. break;
  538. case "Q":
  539. rtv.ValQ = val;
  540. break;
  541. case "DP":
  542. rtv.ValDp = val;
  543. break;
  544. case "DQ":
  545. rtv.ValDq = val;
  546. break;
  547. case "InverseQ":
  548. rtv.ValInverseQ = val;
  549. break;
  550. }
  551. tagM = tagM.NextMatch();
  552. }
  553. if (rtv.KeyModulus == null || rtv.KeyExponent == null)
  554. {
  555. throw new Exception("XML公钥丢失");
  556. }
  557. if (rtv.KeyD != null)
  558. {
  559. if (rtv.ValP == null || rtv.ValQ == null || rtv.ValDp == null || rtv.ValDq == null || rtv.ValInverseQ == null)
  560. {
  561. return new RsaPem(rtv.KeyModulus, rtv.KeyExponent, rtv.KeyD);
  562. }
  563. }
  564. return rtv;
  565. }
  566. private static readonly Regex XmlExp = new(@"\s*<RSAKeyValue>([<>\/\+=\w\s]+)</RSAKeyValue>\s*");
  567. private static readonly Regex XmlTagExp = new(@"<(.+?)>\s*([^<]+?)\s*</");
  568. /// <summary>
  569. /// 将RSA中的密钥对转换成XML格式
  570. /// ,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
  571. /// </summary>
  572. public string ToXML(bool convertToPublic)
  573. {
  574. StringBuilder str = new StringBuilder();
  575. str.Append("<RSAKeyValue>");
  576. str.Append("<Modulus>" + Convert.ToBase64String(KeyModulus) + "</Modulus>");
  577. str.Append("<Exponent>" + Convert.ToBase64String(KeyExponent) + "</Exponent>");
  578. if (KeyD != null && !convertToPublic)
  579. {
  580. /****生成私钥****/
  581. str.Append("<P>" + Convert.ToBase64String(ValP) + "</P>");
  582. str.Append("<Q>" + Convert.ToBase64String(ValQ) + "</Q>");
  583. str.Append("<DP>" + Convert.ToBase64String(ValDp) + "</DP>");
  584. str.Append("<DQ>" + Convert.ToBase64String(ValDq) + "</DQ>");
  585. str.Append("<InverseQ>" + Convert.ToBase64String(ValInverseQ) + "</InverseQ>");
  586. str.Append("<D>" + Convert.ToBase64String(KeyD) + "</D>");
  587. }
  588. str.Append("</RSAKeyValue>");
  589. return str.ToString();
  590. }
  591. }