RsaPem.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. (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 base64 = PemCode.Replace(pem, "");
  227. byte[] data = null;
  228. try
  229. {
  230. data = Convert.FromBase64String(base64);
  231. }
  232. catch
  233. {
  234. }
  235. if (data == null)
  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 Regex PemCode = new Regex(@"--+.+?--+|\s+");
  365. private static readonly byte[] SeqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
  366. private static readonly byte[] Ver = { 0x02, 0x01, 0x00 };
  367. /// <summary>
  368. /// 将RSA中的密钥对转换成PEM格式,usePKCS8=false时返回PKCS#1格式,否则返回PKCS#8格式,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
  369. /// </summary>
  370. public string ToPEM(bool convertToPublic, bool usePKCS8)
  371. {
  372. var ms = new MemoryStream();
  373. //写入一个长度字节码
  374. Action<int> writeLenByte = len =>
  375. {
  376. if (len < 0x80)
  377. {
  378. ms.WriteByte((byte)len);
  379. }
  380. else if (len <= 0xff)
  381. {
  382. ms.WriteByte(0x81);
  383. ms.WriteByte((byte)len);
  384. }
  385. else
  386. {
  387. ms.WriteByte(0x82);
  388. ms.WriteByte((byte)(len >> 8 & 0xff));
  389. ms.WriteByte((byte)(len & 0xff));
  390. }
  391. };
  392. //写入一块数据
  393. Action<byte[]> writeBlock = byts =>
  394. {
  395. var addZero = (byts[0] >> 4) >= 0x8;
  396. ms.WriteByte(0x02);
  397. var len = byts.Length + (addZero ? 1 : 0);
  398. writeLenByte(len);
  399. if (addZero)
  400. {
  401. ms.WriteByte(0x00);
  402. }
  403. ms.Write(byts, 0, byts.Length);
  404. };
  405. //根据后续内容长度写入长度数据
  406. Func<int, byte[], byte[]> writeLen = (index, byts) =>
  407. {
  408. var len = byts.Length - index;
  409. ms.SetLength(0);
  410. ms.Write(byts, 0, index);
  411. writeLenByte(len);
  412. ms.Write(byts, index, len);
  413. return ms.ToArray();
  414. };
  415. Action<MemoryStream, byte[]> writeAll = (stream, byts) =>
  416. {
  417. stream.Write(byts, 0, byts.Length);
  418. };
  419. Func<string, int, string> TextBreak = (text, line) =>
  420. {
  421. var idx = 0;
  422. var len = text.Length;
  423. var str = new StringBuilder();
  424. while (idx < len)
  425. {
  426. if (idx > 0)
  427. {
  428. str.Append('\n');
  429. }
  430. str.Append(idx + line >= len ? text.Substring(idx) : text.Substring(idx, line));
  431. idx += line;
  432. }
  433. return str.ToString();
  434. };
  435. if (KeyD == null || convertToPublic)
  436. {
  437. //生成公钥
  438. //写入总字节数,不含本段长度,额外需要24字节的头,后续计算好填入
  439. ms.WriteByte(0x30);
  440. var index1 = (int)ms.Length;
  441. //固定内容
  442. writeAll(ms, SeqOid);
  443. //从0x00开始的后续长度
  444. ms.WriteByte(0x03);
  445. var index2 = (int)ms.Length;
  446. ms.WriteByte(0x00);
  447. //后续内容长度
  448. ms.WriteByte(0x30);
  449. var index3 = (int)ms.Length;
  450. //写入Modulus
  451. writeBlock(KeyModulus);
  452. //写入Exponent
  453. writeBlock(KeyExponent);
  454. //计算空缺的长度
  455. var bytes = ms.ToArray();
  456. bytes = writeLen(index3, bytes);
  457. bytes = writeLen(index2, bytes);
  458. bytes = writeLen(index1, bytes);
  459. return "-----BEGIN PUBLIC KEY-----\n" + TextBreak(Convert.ToBase64String(bytes), 64) + "\n-----END PUBLIC KEY-----";
  460. }
  461. else
  462. {
  463. /****生成私钥****/
  464. //写入总字节数,后续写入
  465. ms.WriteByte(0x30);
  466. int index1 = (int)ms.Length;
  467. //写入版本号
  468. writeAll(ms, Ver);
  469. //PKCS8 多一段数据
  470. int index2 = -1, index3 = -1;
  471. if (usePKCS8)
  472. {
  473. //固定内容
  474. writeAll(ms, SeqOid);
  475. //后续内容长度
  476. ms.WriteByte(0x04);
  477. index2 = (int)ms.Length;
  478. //后续内容长度
  479. ms.WriteByte(0x30);
  480. index3 = (int)ms.Length;
  481. //写入版本号
  482. writeAll(ms, Ver);
  483. }
  484. //写入数据
  485. writeBlock(KeyModulus);
  486. writeBlock(KeyExponent);
  487. writeBlock(KeyD);
  488. writeBlock(ValP);
  489. writeBlock(ValQ);
  490. writeBlock(ValDp);
  491. writeBlock(ValDq);
  492. writeBlock(ValInverseQ);
  493. //计算空缺的长度
  494. var byts = ms.ToArray();
  495. if (index2 != -1)
  496. {
  497. byts = writeLen(index3, byts);
  498. byts = writeLen(index2, byts);
  499. }
  500. byts = writeLen(index1, byts);
  501. var flag = " PRIVATE KEY";
  502. if (!usePKCS8)
  503. {
  504. flag = " RSA" + flag;
  505. }
  506. return "-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(byts), 64) + "\n-----END" + flag + "-----";
  507. }
  508. }
  509. /// <summary>
  510. /// 将XML格式密钥转成PEM,支持公钥xml、私钥xml
  511. /// 出错将会抛出异常
  512. /// </summary>
  513. public static RsaPem FromXML(string xml)
  514. {
  515. var rtv = new RsaPem();
  516. var xmlM = XmlExp.Match(xml);
  517. if (!xmlM.Success)
  518. {
  519. throw new Exception("XML内容不符合要求");
  520. }
  521. var tagM = XmlTagExp.Match(xmlM.Groups[1].Value);
  522. while (tagM.Success)
  523. {
  524. string tag = tagM.Groups[1].Value;
  525. string b64 = tagM.Groups[2].Value;
  526. byte[] val = Convert.FromBase64String(b64);
  527. switch (tag)
  528. {
  529. case "Modulus":
  530. rtv.KeyModulus = val;
  531. break;
  532. case "Exponent":
  533. rtv.KeyExponent = val;
  534. break;
  535. case "D":
  536. rtv.KeyD = val;
  537. break;
  538. case "P":
  539. rtv.ValP = val;
  540. break;
  541. case "Q":
  542. rtv.ValQ = val;
  543. break;
  544. case "DP":
  545. rtv.ValDp = val;
  546. break;
  547. case "DQ":
  548. rtv.ValDq = val;
  549. break;
  550. case "InverseQ":
  551. rtv.ValInverseQ = val;
  552. break;
  553. }
  554. tagM = tagM.NextMatch();
  555. }
  556. if (rtv.KeyModulus == null || rtv.KeyExponent == null)
  557. {
  558. throw new Exception("XML公钥丢失");
  559. }
  560. if (rtv.KeyD != null)
  561. {
  562. if (rtv.ValP == null || rtv.ValQ == null || rtv.ValDp == null || rtv.ValDq == null || rtv.ValInverseQ == null)
  563. {
  564. return new RsaPem(rtv.KeyModulus, rtv.KeyExponent, rtv.KeyD);
  565. }
  566. }
  567. return rtv;
  568. }
  569. private static readonly Regex XmlExp = new Regex("\\s*<RSAKeyValue>([<>\\/\\+=\\w\\s]+)</RSAKeyValue>\\s*");
  570. private static readonly Regex XmlTagExp = new Regex("<(.+?)>\\s*([^<]+?)\\s*</");
  571. /// <summary>
  572. /// 将RSA中的密钥对转换成XML格式
  573. /// ,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
  574. /// </summary>
  575. public string ToXML(bool convertToPublic)
  576. {
  577. StringBuilder str = new StringBuilder();
  578. str.Append("<RSAKeyValue>");
  579. str.Append("<Modulus>" + Convert.ToBase64String(KeyModulus) + "</Modulus>");
  580. str.Append("<Exponent>" + Convert.ToBase64String(KeyExponent) + "</Exponent>");
  581. if (KeyD != null && !convertToPublic)
  582. {
  583. /****生成私钥****/
  584. str.Append("<P>" + Convert.ToBase64String(ValP) + "</P>");
  585. str.Append("<Q>" + Convert.ToBase64String(ValQ) + "</Q>");
  586. str.Append("<DP>" + Convert.ToBase64String(ValDp) + "</DP>");
  587. str.Append("<DQ>" + Convert.ToBase64String(ValDq) + "</DQ>");
  588. str.Append("<InverseQ>" + Convert.ToBase64String(ValInverseQ) + "</InverseQ>");
  589. str.Append("<D>" + Convert.ToBase64String(KeyD) + "</D>");
  590. }
  591. str.Append("</RSAKeyValue>");
  592. return str.ToString();
  593. }
  594. }
  595. }