RsaKeyHelper.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Org.BouncyCastle.Asn1;
  7. using Org.BouncyCastle.Asn1.Pkcs;
  8. using Org.BouncyCastle.Asn1.X509;
  9. using Org.BouncyCastle.Crypto;
  10. using Org.BouncyCastle.Crypto.Generators;
  11. using Org.BouncyCastle.Crypto.Parameters;
  12. using Org.BouncyCastle.OpenSsl;
  13. using Org.BouncyCastle.Pkcs;
  14. using Org.BouncyCastle.Security;
  15. using Org.BouncyCastle.X509;
  16. using System.IO;
  17. using System.Text.RegularExpressions;
  18. /// <summary>
  19. /// Rsa密钥对生成工具
  20. /// </summary>
  21. public class RsaKeyHelper
  22. {
  23. public static void GenKey(out string publicKey, out string privateKey, out string privateKeyPk8)
  24. {
  25. publicKey = string.Empty;
  26. privateKey = string.Empty;
  27. privateKeyPk8 = string.Empty;
  28. try
  29. {
  30. //RSA密钥对的构造器
  31. RsaKeyPairGenerator r = new RsaKeyPairGenerator();
  32. //RSA密钥构造器的参数
  33. RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
  34. Org.BouncyCastle.Math.BigInteger.ValueOf(3),
  35. new SecureRandom(),
  36. 1024, //密钥长度
  37. 25);
  38. r.Init(param);
  39. AsymmetricCipherKeyPair keyPair = r.GenerateKeyPair();
  40. //获取公钥和密钥
  41. AsymmetricKeyParameter private_key = keyPair.Private;
  42. AsymmetricKeyParameter public_key = keyPair.Public;
  43. if (((RsaKeyParameters)public_key).Modulus.BitLength < 1024)
  44. {
  45. Console.WriteLine("failed key generation (1024) length test");
  46. }
  47. using (TextWriter textWriter = new StringWriter())
  48. {
  49. PemWriter pemWriter = new PemWriter(textWriter);
  50. pemWriter.WriteObject(keyPair.Private);
  51. pemWriter.Writer.Flush();
  52. privateKey = textWriter.ToString();
  53. }
  54. using (TextWriter textpubWriter = new StringWriter())
  55. {
  56. PemWriter pempubWriter = new PemWriter(textpubWriter);
  57. pempubWriter.WriteObject(keyPair.Public);
  58. pempubWriter.Writer.Flush();
  59. publicKey = textpubWriter.ToString();
  60. }
  61. //keyPair = ReadPem(privateKey); // 直接读取字符串生成密码钥
  62. //public_key = keyPair.Public;//公钥
  63. //private_key = keyPair.Private;//私钥
  64. // 前面私钥为pkcs1格式,经过下面处理后,变成pkcs8格式
  65. SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(public_key);
  66. PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(private_key);
  67. Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
  68. byte[] publicInfoByte = asn1ObjectPublic.GetEncoded();
  69. Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
  70. byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded();
  71. var pubkeyb64 = Convert.ToBase64String(publicInfoByte);
  72. // 这里生成的是Pkcs8的密钥
  73. privateKeyPk8 = PrivateKeyPk8Format(Convert.ToBase64String(privateInfoByte));
  74. privateKey = PrivateKeyFormat(privateKey);
  75. publicKey = PublicKeyFormat(publicKey);
  76. }
  77. catch (Exception ex)
  78. {
  79. throw ex;
  80. }
  81. }
  82. /// <summary>
  83. /// 加载Pkcs8格式的私钥
  84. /// </summary>
  85. /// <param name="privateKey"></param>
  86. /// <returns></returns>
  87. public static AsymmetricKeyParameter loadPrivateKeyPk8(string privateKey)
  88. {
  89. try
  90. {
  91. privateKey = KeyClear(privateKey);
  92. byte[] prikey = Convert.FromBase64String(privateKey);
  93. Asn1Object priKeyObj = Asn1Object.FromByteArray(prikey);//这里也可以从流中读取,从本地导入
  94. AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(priKeyObj));
  95. return priKey;
  96. }
  97. catch (Exception)
  98. {
  99. throw new Exception("密钥格式不正确");
  100. }
  101. }
  102. /// <summary>
  103. /// 加载Pkcs1格式的私钥
  104. /// </summary>
  105. /// <param name="privateKey"></param>
  106. /// <returns></returns>
  107. public static AsymmetricKeyParameter loadPrivateKeyPk1(string privateKey)
  108. {
  109. AsymmetricCipherKeyPair keyPair = null;
  110. try
  111. {
  112. keyPair = ReadPem(privateKey); // 直接读取字符串生成密码钥
  113. }
  114. catch (Exception)
  115. {
  116. throw new Exception("密钥格式不正确");
  117. }
  118. try
  119. {
  120. AsymmetricKeyParameter private_key = keyPair.Private;
  121. // 前面私钥为pkcs1格式,经过下面处理后,变成pkcs8格式
  122. PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(private_key);
  123. Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
  124. AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(PrivateKeyInfo.GetInstance(asn1ObjectPrivate));
  125. return priKey;
  126. }
  127. catch (Exception)
  128. {
  129. throw new Exception("加载失败");
  130. }
  131. }
  132. /// <summary>
  133. /// 加载公钥
  134. /// </summary>
  135. /// <param name="publicKey"></param>
  136. /// <returns></returns>
  137. public static AsymmetricKeyParameter loadPublicKey(string publicKey)
  138. {
  139. try
  140. {
  141. publicKey = KeyClear(publicKey);
  142. byte[] pubkey = Convert.FromBase64String(publicKey);
  143. Asn1Object pubKeyObj = Asn1Object.FromByteArray(pubkey);//这里也可以从流中读取,从本地导入
  144. AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(SubjectPublicKeyInfo.GetInstance(pubKeyObj));
  145. return pubKey;
  146. }
  147. catch (Exception)
  148. {
  149. throw new Exception("密钥格式不正确");
  150. }
  151. }
  152. /// <summary>
  153. /// 将Pkcs1格式的私转成Pkcs8格式
  154. /// </summary>
  155. /// <param name="privateKey"></param>
  156. /// <returns></returns>
  157. public static string ConvertPriPk1ToPk8(string privateKey)
  158. {
  159. AsymmetricCipherKeyPair keyPair = null;
  160. try
  161. {
  162. keyPair = ReadPem(privateKey); // 直接读取字符串生成密码钥
  163. }
  164. catch (Exception)
  165. {
  166. throw new Exception("密钥格式不正确");
  167. }
  168. try
  169. {
  170. AsymmetricKeyParameter private_key = keyPair.Private;
  171. AsymmetricKeyParameter public_key = keyPair.Public;
  172. // 前面私钥为pkcs1格式,经过下面处理后,变成pkcs8格式
  173. SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(public_key);
  174. PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(private_key);
  175. Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
  176. byte[] publicInfoByte = asn1ObjectPublic.GetEncoded();
  177. Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
  178. byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded();
  179. var pubkeyb64 = Convert.ToBase64String(publicInfoByte);
  180. // 这里生成的是Pkcs8的密钥
  181. return PrivateKeyFormat(Convert.ToBase64String(privateInfoByte));
  182. }
  183. catch (Exception)
  184. {
  185. throw new Exception("转换失败");
  186. }
  187. }
  188. public static string KeyClear(string key)
  189. {
  190. key = Regex.Replace(key, @"(-----BEGIN PRIVATE KEY-----)|(-----END PRIVATE KEY-----)|(-----BEGIN RSA PRIVATE KEY-----)|(-----END RSA PRIVATE KEY-----)|(-----BEGIN PUBLIC KEY-----)|(-----END PUBLIC KEY-----)|(-----BEGIN RSA PUBLIC KEY-----)|(-----END RSA PUBLIC KEY-----)|\n|\r", "");
  191. return key;
  192. }
  193. private static string PrivateKeyFormat(string privateKey)
  194. {
  195. privateKey = KeyClear(privateKey);
  196. privateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" + privateKey + "\r\n-----END RSA PRIVATE KEY-----";
  197. return privateKey;
  198. }
  199. private static string PrivateKeyPk8Format(string privateKey)
  200. {
  201. privateKey = KeyClear(privateKey);
  202. privateKey = "-----BEGIN PRIVATE KEY-----\r\n" + privateKey + "\r\n-----END PRIVATE KEY-----";
  203. return privateKey;
  204. }
  205. private static string PublicKeyFormat(string publicKey)
  206. {
  207. publicKey = KeyClear(publicKey);
  208. publicKey = "-----BEGIN PUBLIC KEY-----\r\n" + publicKey + "\r\n-----END PUBLIC KEY-----";
  209. return publicKey;
  210. }
  211. static AsymmetricCipherKeyPair ReadPem(string pem)
  212. {
  213. // 判断字符串是否是标准pem
  214. if (!pem.StartsWith("-----BEGIN") && !pem.EndsWith("KEY-----"))
  215. {
  216. pem = PrivateKeyFormat(pem);
  217. }
  218. using (TextReader reader = new StringReader(pem))
  219. {
  220. var obj = new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
  221. return obj as AsymmetricCipherKeyPair;
  222. }
  223. }
  224. }