部分代码来至 https://www.cnblogs.com/dj258/p/6049786.html

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. using Org.BouncyCastle.Asn1.Pkcs;
  7. using Org.BouncyCastle.Asn1.X509;
  8. using Org.BouncyCastle.Crypto.Generators;
  9. using Org.BouncyCastle.Crypto.Parameters;
  10. using Org.BouncyCastle.Math;
  11. using Org.BouncyCastle.Pkcs;
  12. using Org.BouncyCastle.Security;
  13. using Org.BouncyCastle.Crypto.Engines;
  14. using Org.BouncyCastle.X509;
  15. using Org.BouncyCastle.Crypto;
  16. using Org.BouncyCastle.Asn1;
  17. using Org.BouncyCastle.Crypto.Encodings;
  18. using System.IO;
  19. namespace Tool
  20. {
  21. public class RSATool
  22. {
  23.  
  24. public RSATool()
  25. {
  26.  
  27. }
  28. /// <summary>
  29. /// KEY 结构体
  30. /// </summary>
  31. public struct RSAKEY
  32. {
  33. /// <summary>
  34. /// 公钥
  35. /// </summary>
  36. public string PublicKey
  37. {
  38. get;
  39. set;
  40. }
  41. /// <summary>
  42. /// 私钥
  43. /// </summary>
  44. public string PrivateKey
  45. {
  46. get;
  47. set;
  48. }
  49. }
  50. public RSAKEY GetKey()
  51. {
  52. //RSA密钥对的构造器
  53. RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
  54.  
  55. //RSA密钥构造器的参数
  56. RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
  57. Org.BouncyCastle.Math.BigInteger.ValueOf(),
  58. new Org.BouncyCastle.Security.SecureRandom(),
  59. , //密钥长度
  60. );
  61. //用参数初始化密钥构造器
  62. keyGenerator.Init(param);
  63. //产生密钥对
  64. AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
  65. //获取公钥和密钥
  66. AsymmetricKeyParameter publicKey = keyPair.Public;
  67. AsymmetricKeyParameter privateKey = keyPair.Private;
  68.  
  69. SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
  70. PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
  71.  
  72. Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
  73.  
  74. byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");
  75. Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
  76. byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");
  77.  
  78. RSAKEY item = new RSAKEY()
  79. {
  80. PublicKey = Convert.ToBase64String(publicInfoByte),
  81. PrivateKey = Convert.ToBase64String(privateInfoByte)
  82. };
  83. return item;
  84. }
  85. private AsymmetricKeyParameter GetPublicKeyParameter(string s)
  86. {
  87. s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
  88. byte[] publicInfoByte = Convert.FromBase64String(s);
  89. Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入
  90. AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
  91. return pubKey;
  92. }
  93. private AsymmetricKeyParameter GetPrivateKeyParameter(string s)
  94. {
  95. s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
  96. byte[] privateInfoByte = Convert.FromBase64String(s);
  97. // Asn1Object priKeyObj = Asn1Object.FromByteArray(privateInfoByte);//这里也可以从流中读取,从本地导入
  98. // PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
  99. AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
  100. return priKey;
  101. }
  102. public string EncryptByKey(string s, string key, bool isPublic)
  103. {
  104. //非对称加密算法,加解密用
  105. IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
  106. //加密
  107. try
  108. {
  109. engine.Init(true, isPublic ? GetPublicKeyParameter(key) : GetPrivateKeyParameter(key));
  110. byte[] byteData = System.Text.Encoding.UTF8.GetBytes(s);
  111.  
  112. int inputLen = byteData.Length;
  113. MemoryStream ms = new MemoryStream();
  114. int offSet = ;
  115. byte[] cache;
  116. int i = ;
  117. // 对数据分段加密
  118. while (inputLen - offSet > )
  119. {
  120. if (inputLen - offSet > )
  121. {
  122. cache = engine.ProcessBlock(byteData, offSet, );
  123. }
  124. else
  125. {
  126. cache = engine.ProcessBlock(byteData, offSet, inputLen - offSet);
  127. }
  128. ms.Write(cache, , cache.Length);
  129. i++;
  130. offSet = i * ;
  131. }
  132. byte[] encryptedData = ms.ToArray();
  133.  
  134. //var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
  135. return Convert.ToBase64String(encryptedData);
  136. //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
  137. }
  138. catch (Exception ex)
  139. {
  140. return ex.Message;
  141.  
  142. }
  143. }
  144. /// <summary>
  145. /// 解密
  146. /// </summary>
  147. /// <param name="s"></param>
  148. /// <param name="key"></param>
  149. /// <param name="isPublic"></param>
  150. /// <returns></returns>
  151. public string DecryptByPublicKey(string s, string key, bool isPublic)
  152. {
  153. s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
  154. //非对称加密算法,加解密用
  155. IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
  156.  
  157. //加密
  158.  
  159. try
  160. {
  161. engine.Init(false, isPublic ? GetPublicKeyParameter(key) : GetPrivateKeyParameter(key));
  162. byte[] byteData = Convert.FromBase64String(s);
  163.  
  164. int inputLen = byteData.Length;
  165. MemoryStream ms = new MemoryStream();
  166. int offSet = ;
  167. byte[] cache;
  168. int i = ;
  169. // 对数据分段加密
  170. while (inputLen - offSet > )
  171. {
  172. if (inputLen - offSet > )
  173. {
  174. cache = engine.ProcessBlock(byteData, offSet, );
  175. }
  176. else
  177. {
  178. cache = engine.ProcessBlock(byteData, offSet, inputLen - offSet);
  179. }
  180. ms.Write(cache, , cache.Length);
  181. i++;
  182. offSet = i * ;
  183. }
  184. byte[] encryptedData = ms.ToArray();
  185.  
  186. //var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
  187. return Encoding.UTF8.GetString(ms.ToArray());
  188. //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
  189. }
  190. catch (Exception ex)
  191. {
  192. return ex.Message;
  193.  
  194. }
  195. }
  196. /// <summary>
  197. /// 签名
  198. /// </summary>
  199. /// <param name="data">数据</param>
  200. /// <param name="key">密匙</param>
  201. /// <returns></returns>
  202. public string SignByPrivateKey(string data, string key)
  203. {
  204. AsymmetricKeyParameter priKey = GetPrivateKeyParameter(key);
  205. byte[] byteData = System.Text.Encoding.UTF8.GetBytes(data);
  206.  
  207. ISigner normalSig = SignerUtilities.GetSigner("SHA1WithRSA");
  208. normalSig.Init(true, priKey);
  209. normalSig.BlockUpdate(byteData, , data.Length);
  210. byte[] normalResult = normalSig.GenerateSignature(); //签名结果
  211. return Convert.ToBase64String(normalResult);
  212. //return System.Text.Encoding.UTF8.GetString(normalResult);
  213. }
  214.  
  215. /// <summary>
  216. /// 验签
  217. /// </summary>
  218. /// <param name="plainData">验证数据</param>
  219. /// <param name="sign">签名</param>
  220. /// <param name="key">公匙</param>
  221. /// <returns></returns>
  222. public bool ValidationPublicKey(string plainData, string sign, string key)
  223. {
  224. AsymmetricKeyParameter priKey = GetPublicKeyParameter(key);
  225.  
  226. byte[] signBytes = Convert.FromBase64String(sign);
  227. byte[] plainBytes = Encoding.UTF8.GetBytes(plainData);
  228.  
  229. ISigner verifier = SignerUtilities.GetSigner("SHA1WithRSA");
  230. verifier.Init(false, priKey);
  231. verifier.BlockUpdate(plainBytes, , plainBytes.Length);
  232.  
  233. return verifier.VerifySignature(signBytes); //验签结果
  234. }
  235. }
  236. }

亲测可用

C# Pkcs8 1024位 加密 解密 签名 解签的更多相关文章

  1. RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密

    原文:RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密 C#在using System.Security.Cryptograph ...

  2. C# RSACryptoServiceProvider加密解密签名验签和DESCryptoServic

    C#在using System.Security.Cryptography下有 DESCryptoServiceProvider RSACryptoServiceProvider DESCryptoS ...

  3. js rsa sign使用笔记(加密,解密,签名,验签)

    你将会收获: js如何加密, 解密 js如何签名, 验签 js和Java交互如何相互解密, 验签(重点) 通过谷歌, 发现jsrsasign库使用者较多. 查看api发现这个库功能很健全. 本文使用方 ...

  4. Java RSA 加密 解密 签名 验签

    原文:http://gaofulai1988.iteye.com/blog/2262802 import java.io.FileInputStream; import java.io.FileOut ...

  5. iOS使用Security.framework进行RSA 加密解密签名和验证签名

    iOS 上 Security.framework为我们提供了安全方面相关的api: Security框架提供的RSA在iOS上使用的一些小结 支持的RSA keySize 大小有:512,768,10 ...

  6. .NET Core 使用RSA算法 加密/解密/签名/验证签名

    前言 前不久移植了支付宝官方的SDK,以适用ASP.NET Core使用支付宝支付,但是最近有好几位用户反应在Linux下使用会出错,调试发现是RSA加密的错误,下面具体讲一讲. RSA在.NET C ...

  7. 使用 GPG 对数据进行加密解密签名

    一:使用 GPG 对数据进行加密解密签名 基本的工具使用 1. GPG 是GNUPG 免费开源的gpg加密工具,和同pgp兼容,pgp收费. 2. 在mac上使用https://gpgtools.or ...

  8. RSA加密解密与加签验签

    RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest).阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的.1987年7月首次在美国公布 ...

  9. 支付接口中常用的加密解密以及验签rsa,md5,sha

    一.常用加密类型分类 1.对称加密:采用单钥对信息进行加密和解密,即同一个秘钥既可以对信息进行加密,也可以进行解密.此类型称之为对称加密.特点速度快,常用于对大量数据信息或文件加密时使用.常用例子:D ...

随机推荐

  1. Linux系统中nc工具那些不为人知的用法

    Linux nc命令用法 参考地址:https://www.cnblogs.com/jjzd/p/6306273.html -g<网关>:设置路由器跃程通信网关,最多设置8个; -G< ...

  2. PHP导出成PDF你用哪个插件

    准备工作 首先查询了相关的类库,有FPDF,zendPDF,TcPDF等等.首先看了下先选择了FPDF,可以说除了中文字符以外没有什么问题,中文乱码而且看了下最新版本没有很好的解决方案,所以只能放弃. ...

  3. poj 3281 Dining (Dinic)

    Dining Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 22572   Accepted: 10015 Descript ...

  4. windows 10上源码编译libjpeg-turbo和使用教程 | compile and use libjpeg-turbo on windows 10

    本文首发于个人博客https://kezunlin.me/post/83828674/,欢迎阅读! compile and use libjpeg-turbo on windows 10 Series ...

  5. Class文件结构全面解析(下)

    接上回书 书接上一回,分享了Class文件的主要构成,同时也详细分析了魔数.次版本号.主版本号.常量池集合.访问标志的构造,接下来我们就继续学习. 欢迎关注微信公众号:万猫学社,每周一分享Java技术 ...

  6. Orleans 3.0 为我们带来了什么

    原文:https://devblogs.microsoft.com/dotnet/orleans-3-0/ 作者:Reuben Bond,Orleans首席软件开发工程师 翻译:艾心 这是一篇来自Or ...

  7. jinjia2

    ansible-playbook --become --become-method=su -K copy.yml - hosts: web remote_user: ansible tasks: - ...

  8. Redis 数据结构

    一.Redis简介 Redis是一款基于key-value的高性能NoSQL数据库,开源免费,遵守BSD协议.支持string(字符串) . hash(哈希) .list(列表) . set(集合) ...

  9. Liunx 安装配置zsh和oh-my-zsh 替换 bash

    一.前言 本文将基于 Liunx 环境安装配置zsh 和 oh-my-zsh 替换 bash oh my zsh Liunx默认shell是单调的bash,而zsh比较高大上,bash有的功能,zsh ...

  10. css优先级之important

    css优先级之important