RsaPem.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Numerics;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. namespace Masuit.Tools.Security
  9. {
  10. /// <summary>
  11. /// RSA PEM格式密钥对的解析和导出
  12. /// </summary>
  13. public 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. BigInteger t = p;
  109. p = q;
  110. q = t;
  111. }
  112. BigInteger exp1 = d % (p - BigInteger.One);
  113. BigInteger exp2 = d % (q - BigInteger.One);
  114. BigInteger coeff = BigInteger.ModPow(q, p - 2, p);
  115. ValP = BigB(p); //prime1
  116. ValQ = BigB(q); //prime2
  117. ValDp = BigB(exp1); //exponent1
  118. ValDq = BigB(exp2); //exponent2
  119. ValInverseQ = BigB(coeff); //coefficient
  120. }
  121. }
  122. /// <summary>
  123. /// 密钥位数
  124. /// </summary>
  125. public int KeySize => KeyModulus.Length * 8;
  126. /// <summary>
  127. /// 是否包含私钥
  128. /// </summary>
  129. public bool HasPrivate => KeyD != null;
  130. /// <summary>
  131. /// 将PEM中的公钥私钥转成RSA对象,如果未提供私钥,RSA中就只包含公钥
  132. /// </summary>
  133. public RSACryptoServiceProvider GetRSA()
  134. {
  135. //var rsaParams = System.Security.Cryptography.RSA.Create();
  136. //rsaParams.Flags = CspProviderFlags.UseMachineKeyStore;
  137. var rsa = new RSACryptoServiceProvider();
  138. var param = new RSAParameters
  139. {
  140. Modulus = KeyModulus,
  141. Exponent = KeyExponent
  142. };
  143. if (KeyD != null)
  144. {
  145. param.D = KeyD;
  146. param.P = ValP;
  147. param.Q = ValQ;
  148. param.DP = ValDp;
  149. param.DQ = ValDq;
  150. param.InverseQ = ValInverseQ;
  151. }
  152. rsa.ImportParameters(param);
  153. return rsa;
  154. }
  155. /// <summary>
  156. /// 转成正整数,如果是负数,需要加前导0转成正整数
  157. /// </summary>
  158. public static BigInteger BigX(byte[] bigb)
  159. {
  160. if (bigb[0] > 127)
  161. {
  162. byte[] c = new byte[bigb.Length + 1];
  163. Array.Copy(bigb, 0, c, 1, bigb.Length);
  164. bigb = c;
  165. }
  166. return new BigInteger(bigb.Reverse().ToArray()); //C#的二进制是反的
  167. }
  168. /// <summary>
  169. /// BigInt导出byte整数首字节>0x7F的会加0前导,保证正整数,因此需要去掉0
  170. /// </summary>
  171. public static byte[] BigB(BigInteger bigx)
  172. {
  173. byte[] val = bigx.ToByteArray().Reverse().ToArray(); //C#的二进制是反的
  174. if (val[0] == 0)
  175. {
  176. byte[] c = new byte[val.Length - 1];
  177. Array.Copy(val, 1, c, 0, c.Length);
  178. val = c;
  179. }
  180. return val;
  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 base64 = PemCode.Replace(pem, "");
  229. byte[] data = null;
  230. try
  231. {
  232. data = Convert.FromBase64String(base64);
  233. }
  234. catch
  235. {
  236. }
  237. if (data == null)
  238. {
  239. throw new Exception("PEM内容无效");
  240. }
  241. var idx = 0;
  242. //读取长度
  243. Func<byte, int> readLen = (first) =>
  244. {
  245. if (data[idx] == first)
  246. {
  247. idx++;
  248. if (data[idx] == 0x81)
  249. {
  250. idx++;
  251. return data[idx++];
  252. }
  253. if (data[idx] == 0x82)
  254. {
  255. idx++;
  256. return ((data[idx++]) << 8) + data[idx++];
  257. }
  258. if (data[idx] < 0x80)
  259. {
  260. return data[idx++];
  261. }
  262. }
  263. throw new Exception("PEM未能提取到数据");
  264. };
  265. //读取块数据
  266. Func<byte[]> readBlock = () =>
  267. {
  268. var len = readLen(0x02);
  269. if (data[idx] == 0x00)
  270. {
  271. idx++;
  272. len--;
  273. }
  274. var val = new byte[len];
  275. for (var i = 0; i < len; i++)
  276. {
  277. val[i] = data[idx + i];
  278. }
  279. idx += len;
  280. return val;
  281. };
  282. //比较data从idx位置开始是否是byts内容
  283. Func<byte[], bool> eq = (byts) =>
  284. {
  285. for (var i = 0; i < byts.Length; i++, idx++)
  286. {
  287. if (idx >= data.Length)
  288. {
  289. return false;
  290. }
  291. if (byts[i] != data[idx])
  292. {
  293. return false;
  294. }
  295. }
  296. return true;
  297. };
  298. if (pem.Contains("PUBLIC KEY"))
  299. {
  300. //使用公钥
  301. //读取数据总长度
  302. readLen(0x30);
  303. //看看有没有oid
  304. var idx2 = idx;
  305. if (eq(SeqOid))
  306. {
  307. //读取1长度
  308. readLen(0x03);
  309. idx++; //跳过0x00
  310. //读取2长度
  311. readLen(0x30);
  312. }
  313. else
  314. {
  315. idx = idx2;
  316. }
  317. //Modulus
  318. param.KeyModulus = readBlock();
  319. //Exponent
  320. param.KeyExponent = readBlock();
  321. }
  322. else if (pem.Contains("PRIVATE KEY"))
  323. {
  324. //使用私钥
  325. //读取数据总长度
  326. readLen(0x30);
  327. //读取版本号
  328. if (!eq(Ver))
  329. {
  330. throw new Exception("PEM未知版本");
  331. }
  332. //检测PKCS8
  333. var idx2 = idx;
  334. if (eq(SeqOid))
  335. {
  336. //读取1长度
  337. readLen(0x04);
  338. //读取2长度
  339. readLen(0x30);
  340. //读取版本号
  341. if (!eq(Ver))
  342. {
  343. throw new Exception("PEM版本无效");
  344. }
  345. }
  346. else
  347. {
  348. idx = idx2;
  349. }
  350. //读取数据
  351. param.KeyModulus = readBlock();
  352. param.KeyExponent = readBlock();
  353. param.KeyD = readBlock();
  354. param.ValP = readBlock();
  355. param.ValQ = readBlock();
  356. param.ValDp = readBlock();
  357. param.ValDq = readBlock();
  358. param.ValInverseQ = readBlock();
  359. }
  360. else
  361. {
  362. throw new Exception("pem需要BEGIN END标头");
  363. }
  364. return param;
  365. }
  366. private static readonly Regex PemCode = new Regex(@"--+.+?--+|\s+");
  367. private static readonly byte[] SeqOid = {
  368. 0x30,
  369. 0x0D,
  370. 0x06,
  371. 0x09,
  372. 0x2A,
  373. 0x86,
  374. 0x48,
  375. 0x86,
  376. 0xF7,
  377. 0x0D,
  378. 0x01,
  379. 0x01,
  380. 0x01,
  381. 0x05,
  382. 0x00
  383. };
  384. private static readonly byte[] Ver = {
  385. 0x02,
  386. 0x01,
  387. 0x00
  388. };
  389. /// <summary>
  390. /// 将RSA中的密钥对转换成PEM格式,usePKCS8=false时返回PKCS#1格式,否则返回PKCS#8格式,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
  391. /// </summary>
  392. public string ToPEM(bool convertToPublic, bool usePKCS8)
  393. {
  394. var ms = new MemoryStream();
  395. //写入一个长度字节码
  396. Action<int> writeLenByte = len =>
  397. {
  398. if (len < 0x80)
  399. {
  400. ms.WriteByte((byte)len);
  401. }
  402. else if (len <= 0xff)
  403. {
  404. ms.WriteByte(0x81);
  405. ms.WriteByte((byte)len);
  406. }
  407. else
  408. {
  409. ms.WriteByte(0x82);
  410. ms.WriteByte((byte)(len >> 8 & 0xff));
  411. ms.WriteByte((byte)(len & 0xff));
  412. }
  413. };
  414. //写入一块数据
  415. Action<byte[]> writeBlock = byts =>
  416. {
  417. var addZero = (byts[0] >> 4) >= 0x8;
  418. ms.WriteByte(0x02);
  419. var len = byts.Length + (addZero ? 1 : 0);
  420. writeLenByte(len);
  421. if (addZero)
  422. {
  423. ms.WriteByte(0x00);
  424. }
  425. ms.Write(byts, 0, byts.Length);
  426. };
  427. //根据后续内容长度写入长度数据
  428. Func<int, byte[], byte[]> writeLen = (index, byts) =>
  429. {
  430. var len = byts.Length - index;
  431. ms.SetLength(0);
  432. ms.Write(byts, 0, index);
  433. writeLenByte(len);
  434. ms.Write(byts, index, len);
  435. return ms.ToArray();
  436. };
  437. Action<MemoryStream, byte[]> writeAll = (stream, byts) =>
  438. {
  439. stream.Write(byts, 0, byts.Length);
  440. };
  441. Func<string, int, string> TextBreak = (text, line) =>
  442. {
  443. var idx = 0;
  444. var len = text.Length;
  445. var str = new StringBuilder();
  446. while (idx < len)
  447. {
  448. if (idx > 0)
  449. {
  450. str.Append('\n');
  451. }
  452. str.Append(idx + line >= len ? text.Substring(idx) : text.Substring(idx, line));
  453. idx += line;
  454. }
  455. return str.ToString();
  456. };
  457. if (KeyD == null || convertToPublic)
  458. {
  459. //生成公钥
  460. //写入总字节数,不含本段长度,额外需要24字节的头,后续计算好填入
  461. ms.WriteByte(0x30);
  462. var index1 = (int)ms.Length;
  463. //固定内容
  464. writeAll(ms, SeqOid);
  465. //从0x00开始的后续长度
  466. ms.WriteByte(0x03);
  467. var index2 = (int)ms.Length;
  468. ms.WriteByte(0x00);
  469. //后续内容长度
  470. ms.WriteByte(0x30);
  471. var index3 = (int)ms.Length;
  472. //写入Modulus
  473. writeBlock(KeyModulus);
  474. //写入Exponent
  475. writeBlock(KeyExponent);
  476. //计算空缺的长度
  477. var bytes = ms.ToArray();
  478. bytes = writeLen(index3, bytes);
  479. bytes = writeLen(index2, bytes);
  480. bytes = writeLen(index1, bytes);
  481. return "-----BEGIN PUBLIC KEY-----\n" + TextBreak(Convert.ToBase64String(bytes), 64) + "\n-----END PUBLIC KEY-----";
  482. }
  483. else
  484. {
  485. /****生成私钥****/
  486. //写入总字节数,后续写入
  487. ms.WriteByte(0x30);
  488. int index1 = (int)ms.Length;
  489. //写入版本号
  490. writeAll(ms, Ver);
  491. //PKCS8 多一段数据
  492. int index2 = -1, index3 = -1;
  493. if (usePKCS8)
  494. {
  495. //固定内容
  496. writeAll(ms, SeqOid);
  497. //后续内容长度
  498. ms.WriteByte(0x04);
  499. index2 = (int)ms.Length;
  500. //后续内容长度
  501. ms.WriteByte(0x30);
  502. index3 = (int)ms.Length;
  503. //写入版本号
  504. writeAll(ms, Ver);
  505. }
  506. //写入数据
  507. writeBlock(KeyModulus);
  508. writeBlock(KeyExponent);
  509. writeBlock(KeyD);
  510. writeBlock(ValP);
  511. writeBlock(ValQ);
  512. writeBlock(ValDp);
  513. writeBlock(ValDq);
  514. writeBlock(ValInverseQ);
  515. //计算空缺的长度
  516. var byts = ms.ToArray();
  517. if (index2 != -1)
  518. {
  519. byts = writeLen(index3, byts);
  520. byts = writeLen(index2, byts);
  521. }
  522. byts = writeLen(index1, byts);
  523. var flag = " PRIVATE KEY";
  524. if (!usePKCS8)
  525. {
  526. flag = " RSA" + flag;
  527. }
  528. return "-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(byts), 64) + "\n-----END" + flag + "-----";
  529. }
  530. }
  531. /// <summary>
  532. /// 将XML格式密钥转成PEM,支持公钥xml、私钥xml
  533. /// 出错将会抛出异常
  534. /// </summary>
  535. public static RsaPem FromXML(string xml)
  536. {
  537. var rtv = new RsaPem();
  538. var xmlM = XmlExp.Match(xml);
  539. if (!xmlM.Success)
  540. {
  541. throw new Exception("XML内容不符合要求");
  542. }
  543. var tagM = XmlTagExp.Match(xmlM.Groups[1].Value);
  544. while (tagM.Success)
  545. {
  546. string tag = tagM.Groups[1].Value;
  547. string b64 = tagM.Groups[2].Value;
  548. byte[] val = Convert.FromBase64String(b64);
  549. switch (tag)
  550. {
  551. case "Modulus":
  552. rtv.KeyModulus = val;
  553. break;
  554. case "Exponent":
  555. rtv.KeyExponent = val;
  556. break;
  557. case "D":
  558. rtv.KeyD = val;
  559. break;
  560. case "P":
  561. rtv.ValP = val;
  562. break;
  563. case "Q":
  564. rtv.ValQ = val;
  565. break;
  566. case "DP":
  567. rtv.ValDp = val;
  568. break;
  569. case "DQ":
  570. rtv.ValDq = val;
  571. break;
  572. case "InverseQ":
  573. rtv.ValInverseQ = val;
  574. break;
  575. }
  576. tagM = tagM.NextMatch();
  577. }
  578. if (rtv.KeyModulus == null || rtv.KeyExponent == null)
  579. {
  580. throw new Exception("XML公钥丢失");
  581. }
  582. if (rtv.KeyD != null)
  583. {
  584. if (rtv.ValP == null || rtv.ValQ == null || rtv.ValDp == null || rtv.ValDq == null || rtv.ValInverseQ == null)
  585. {
  586. return new RsaPem(rtv.KeyModulus, rtv.KeyExponent, rtv.KeyD);
  587. }
  588. }
  589. return rtv;
  590. }
  591. private static readonly Regex XmlExp = new Regex("\\s*<RSAKeyValue>([<>\\/\\+=\\w\\s]+)</RSAKeyValue>\\s*");
  592. private static readonly Regex XmlTagExp = new Regex("<(.+?)>\\s*([^<]+?)\\s*</");
  593. /// <summary>
  594. /// 将RSA中的密钥对转换成XML格式
  595. /// ,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
  596. /// </summary>
  597. public string ToXML(bool convertToPublic)
  598. {
  599. StringBuilder str = new StringBuilder();
  600. str.Append("<RSAKeyValue>");
  601. str.Append("<Modulus>" + Convert.ToBase64String(KeyModulus) + "</Modulus>");
  602. str.Append("<Exponent>" + Convert.ToBase64String(KeyExponent) + "</Exponent>");
  603. if (KeyD == null || convertToPublic)
  604. {
  605. /****生成公钥****/
  606. //NOOP
  607. }
  608. else
  609. {
  610. /****生成私钥****/
  611. str.Append("<P>" + Convert.ToBase64String(ValP) + "</P>");
  612. str.Append("<Q>" + Convert.ToBase64String(ValQ) + "</Q>");
  613. str.Append("<DP>" + Convert.ToBase64String(ValDp) + "</DP>");
  614. str.Append("<DQ>" + Convert.ToBase64String(ValDq) + "</DQ>");
  615. str.Append("<InverseQ>" + Convert.ToBase64String(ValInverseQ) + "</InverseQ>");
  616. str.Append("<D>" + Convert.ToBase64String(KeyD) + "</D>");
  617. }
  618. str.Append("</RSAKeyValue>");
  619. return str.ToString();
  620. }
  621. }
  622. }