1. namespace com._80community.unittest.CUP
  2. {
  3. /// <summary>
  4. /// CUP Client
  5. /// </summary>
  6. public interface IClient
  7. {
  8. /// <summary>
  9. /// Generate Signature
  10. /// </summary>
  11. /// <param name="content">contents requiring signatures</param>
  12. /// <param name="privateKey">private key</param>
  13. /// <param name="inputCharset">coding format</param>
  14. /// <returns>the signature string</returns>
  15. string Sign(string content, string inputCharset);
  16. /// <summary>
  17. /// Verification Signature
  18. /// </summary>
  19. /// <param name="content">contents requiring signature verification </param>
  20. /// <param name="signedString">the signature string</param>
  21. /// <param name="publicKey">public key</param>
  22. /// <param name="inputCharset">coding format</param>
  23. /// <returns></returns>
  24. bool Verify(string content, string signedString, string inputCharset);
  25.  
  26. }
  27. }
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5.  
  6. namespace com._80community.unittest.CUP
  7. {
  8. /// <summary>
  9. /// CUP Client
  10. /// </summary>
  11. public class Client : IClient
  12. {
  13. private string serverUrl;
  14. private string merchantNo;
  15. private string privateKey;
  16. private string publicKey;
  17.  
  18. public Client(string serverUrl, string merchantNo, string privateKey, string publicKey)
  19. {
  20. this.serverUrl = serverUrl;
  21. this.merchantNo = merchantNo;
  22. this.privateKey = privateKey;
  23. this.publicKey = publicKey;
  24. }
  25.  
  26. #region Generate Signature
  27.  
  28. // <summary>
  29. /// Generate Signature
  30. /// </summary>
  31. public string Sign(string content, string inputCharset = "UTF-8")
  32. {
  33. try
  34. {
  35. Encoding code = Encoding.GetEncoding(inputCharset);
  36. byte[] data = code.GetBytes(content);
  37. RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
  38. SHA1 sh = new SHA1CryptoServiceProvider();
  39.  
  40. byte[] signData = rsa.SignData(data, sh);
  41. return Convert.ToBase64String(signData);
  42. }
  43. catch
  44. {
  45. return "";
  46. }
  47. }
  48.  
  49. #region Internal Method for Generating Signature
  50. /// <summary>
  51. /// 把PKCS8格式的私钥转成PEK格式私钥,然后再填充RSACryptoServiceProvider对象
  52. /// </summary>
  53. /// <param name="pkcs8"></param>
  54. /// <returns></returns>
  55. internal RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8)
  56. {
  57. byte[] seqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
  58. byte[] seq = new byte[];
  59.  
  60. MemoryStream mem = new MemoryStream(pkcs8);
  61. RSACryptoServiceProvider rsacsp = null;
  62.  
  63. int lenStream = (int)mem.Length;
  64. BinaryReader binReader = new BinaryReader(mem);
  65. byte bt = ;
  66. ushort twoBytes = ;
  67.  
  68. try
  69. {
  70. twoBytes = binReader.ReadUInt16();
  71. if (twoBytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
  72. binReader.ReadByte(); //advance 1 byte
  73. else if (twoBytes == 0x8230)
  74. binReader.ReadInt16(); //advance 2 bytes
  75. else
  76. return null;
  77.  
  78. bt = binReader.ReadByte();
  79. if (bt != 0x02)
  80. return null;
  81.  
  82. twoBytes = binReader.ReadUInt16();
  83.  
  84. if (twoBytes != 0x0001)
  85. return null;
  86.  
  87. seq = binReader.ReadBytes(); //read the Sequence OID
  88. if (!CompareBytearrays(seq, seqOID)) //make sure Sequence for OID is correct
  89. return null;
  90.  
  91. bt = binReader.ReadByte();
  92. if (bt != 0x04) //expect an Octet string
  93. return null;
  94.  
  95. bt = binReader.ReadByte(); //read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count
  96. if (bt == 0x81)
  97. binReader.ReadByte();
  98. else
  99. if (bt == 0x82)
  100. binReader.ReadUInt16();
  101.  
  102. // at this stage, the remaining sequence should be the RSA private key
  103. byte[] rsaprivkey = binReader.ReadBytes((int)(lenStream - mem.Position));
  104. rsacsp = DecodeRSAPrivateKey(rsaprivkey);
  105.  
  106. return rsacsp;
  107. }
  108. catch
  109. {
  110. return null;
  111. }
  112. finally
  113. {
  114. binReader.Close();
  115. }
  116. }
  117.  
  118. private bool CompareBytearrays(byte[] a, byte[] b)
  119. {
  120. if (a.Length != b.Length)
  121. return false;
  122. int i = ;
  123. foreach (byte c in a)
  124. {
  125. if (c != b[i])
  126. return false;
  127. i++;
  128. }
  129. return true;
  130. }
  131.  
  132. /// <summary>
  133. /// PEM格式私钥转RSACryptoServiceProvider对象
  134. /// </summary>
  135. /// <param name="privkey"></param>
  136. /// <returns></returns>
  137. internal RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
  138. {
  139. byte[] modulus, e, d, p, q, dp, dq, iq;
  140.  
  141. // Set up stream to decode the asn.1 encoded RSA private key
  142. MemoryStream mem = new MemoryStream(privkey);
  143.  
  144. // wrap Memory Stream with BinaryReader for easy reading
  145. BinaryReader binReader = new BinaryReader(mem);
  146. byte bt = ;
  147. ushort twoBytes = ;
  148. int elems = ;
  149. try
  150. {
  151. twoBytes = binReader.ReadUInt16();
  152. if (twoBytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
  153. {
  154. binReader.ReadByte(); // advance 1 byte
  155. }
  156. else if (twoBytes == 0x8230)
  157. {
  158. binReader.ReadInt16(); // advance 2 byte
  159. }
  160. else
  161. {
  162. return null;
  163. }
  164.  
  165. twoBytes = binReader.ReadUInt16();
  166. if (twoBytes != 0x0102) // version number
  167. return null;
  168. bt = binReader.ReadByte();
  169. if (bt != 0x00)
  170. return null;
  171.  
  172. // all private key components are Integer sequences
  173. elems = GetIntegerSize(binReader);
  174. modulus = binReader.ReadBytes(elems);
  175.  
  176. elems = GetIntegerSize(binReader);
  177. e = binReader.ReadBytes(elems);
  178.  
  179. elems = GetIntegerSize(binReader);
  180. d = binReader.ReadBytes(elems);
  181.  
  182. elems = GetIntegerSize(binReader);
  183. p = binReader.ReadBytes(elems);
  184.  
  185. elems = GetIntegerSize(binReader);
  186. q = binReader.ReadBytes(elems);
  187.  
  188. elems = GetIntegerSize(binReader);
  189. dp = binReader.ReadBytes(elems);
  190.  
  191. elems = GetIntegerSize(binReader);
  192. dq = binReader.ReadBytes(elems);
  193.  
  194. elems = GetIntegerSize(binReader);
  195. iq = binReader.ReadBytes(elems);
  196.  
  197. // ------- create RSACryptoServiceProvider instance and initialize with public key -----
  198. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
  199. RSAParameters rsaParams = new RSAParameters();
  200. rsaParams.Modulus = modulus;
  201. rsaParams.Exponent = e;
  202. rsaParams.D = d;
  203. rsaParams.P = p;
  204. rsaParams.Q = q;
  205. rsaParams.DP = dp;
  206. rsaParams.DQ = dq;
  207. rsaParams.InverseQ = iq;
  208. rsa.ImportParameters(rsaParams);
  209. return rsa;
  210. }
  211. catch (Exception)
  212. {
  213. return null;
  214. }
  215. finally
  216. {
  217. binReader.Close();
  218. }
  219. }
  220.  
  221. internal int GetIntegerSize(BinaryReader binReader)
  222. {
  223. byte bt = ;
  224. byte lowByte = 0x00;
  225. byte highByte = 0x00;
  226. int count = ;
  227. bt = binReader.ReadByte();
  228. if (bt != 0x02) //expect integer
  229. return ;
  230. bt = binReader.ReadByte();
  231.  
  232. if (bt == 0x81)
  233. {
  234. count = binReader.ReadByte(); // data size in next byte
  235. }
  236. else
  237. {
  238. if (bt == 0x82)
  239. {
  240. highByte = binReader.ReadByte(); // data size in next 2 bytes
  241. lowByte = binReader.ReadByte();
  242. byte[] modint = { lowByte, highByte, 0x00, 0x00 };
  243. count = BitConverter.ToInt32(modint, );
  244. }
  245. else
  246. {
  247. count = bt; // we already have the data size
  248. }
  249. }
  250.  
  251. while (binReader.ReadByte() == 0x00)
  252. { //remove high order zeros in data
  253. count -= ;
  254. }
  255. binReader.BaseStream.Seek(-, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte
  256. return count;
  257. }
  258.  
  259. #endregion
  260.  
  261. /// <summary>
  262. /// 解析PKCS8格式的pem私钥
  263. /// </summary>
  264. /// <param name="pemstr"></param>
  265. /// <returns></returns>
  266. internal RSACryptoServiceProvider DecodePemPrivateKey(string pemstr)
  267. {
  268. RSACryptoServiceProvider rsa = null;
  269. byte[] pkcs8PrivteKey = Convert.FromBase64String(pemstr);
  270. if (pkcs8PrivteKey != null)
  271. {
  272. rsa = DecodePrivateKeyInfo(pkcs8PrivteKey);
  273. }
  274. return rsa;
  275. }
  276.  
  277. #endregion
  278.  
  279. #region Verification Signature
  280.  
  281. /// <summary>
  282. /// Verification Signature
  283. /// </summary>
  284. public bool Verify(string content, string signedString, string inputCharset = "UTF-8")
  285. {
  286. bool result = false;
  287.  
  288. Encoding code = Encoding.GetEncoding(inputCharset);
  289. byte[] data = code.GetBytes(content);
  290. byte[] soureData = Convert.FromBase64String(signedString);
  291. RSAParameters paraPub = ConvertFromPublicKey(publicKey);
  292. RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
  293. rsaPub.ImportParameters(paraPub);
  294. SHA1 sh = new SHA1CryptoServiceProvider();
  295. result = rsaPub.VerifyData(data, sh, soureData);
  296. return result;
  297. }
  298.  
  299. /// <summary>
  300. ///
  301. /// </summary>
  302. /// <param name="pemFileConent"></param>
  303. /// <returns></returns>
  304. internal RSAParameters ConvertFromPublicKey(string pempublicKey)
  305. {
  306. byte[] keyData = Convert.FromBase64String(pempublicKey);
  307. if (keyData.Length < )
  308. {
  309. throw new ArgumentException("pem file content is incorrect.");
  310. }
  311. byte[] pemModulus = new byte[];
  312. byte[] pemPublicExponent = new byte[];
  313. Array.Copy(keyData, , pemModulus, , );
  314. Array.Copy(keyData, , pemPublicExponent, , );
  315. RSAParameters para = new RSAParameters();
  316. para.Modulus = pemModulus;
  317. para.Exponent = pemPublicExponent;
  318. return para;
  319. }
  320.  
  321. public string DecodeBase64(string code_type, string code)
  322. {
  323. string decode = "";
  324. byte[] bytes = Convert.FromBase64String(code); //将2进制编码转换为8位无符号整数数组.
  325. try
  326. {
  327. decode = Encoding.GetEncoding(code_type).GetString(bytes); //将指定字节数组中的一个字节序列解码为一个字符串。
  328. }
  329. catch
  330. {
  331. decode = code;
  332. }
  333. return decode;
  334. }
  335.  
  336. #endregion
  337.  
  338. #region Get the value of the key from the key file
  339. /// <summary>
  340. /// Get the value of the key from the key file
  341. /// </summary>
  342. /// <param name="type">RSA PRIVATE KEY/RSA PUBLIC KEY</param>
  343. /// <param name="pemUrl">url of the key file</param>
  344. /// <returns>base64 string</returns>
  345. static public string GetKeyFromPem(string type, string pemUrl)
  346. {
  347. string base64 = string.Empty;
  348. using (FileStream fs = File.OpenRead(pemUrl))
  349. {
  350. byte[] data1 = new byte[fs.Length];
  351. fs.Read(data1, , data1.Length);
  352. string pem = Encoding.UTF8.GetString(data1);
  353. string header = String.Format("-----BEGIN {0}-----\\n", type);
  354. string footer = String.Format("-----END {0}-----", type);
  355. int start = pem.IndexOf(header) + header.Length;
  356. int end = pem.IndexOf(footer, start);
  357. base64 = pem.Substring(start, (end - start));
  358. }
  359. return base64;
  360. }
  361. #endregion
  362.  
  363. }
  364. }
  1. using System.Configuration;
  2.  
  3. namespace Entity.Common
  4. {
  5. static public partial class AppConfig
  6. {
  7. static public string GetServerUrl
  8. {
  9. get { return ConfigurationManager.AppSettings["CupServerUrl"]; }
  10. }
  11. static public string GetMerchantNo
  12. {
  13. get { return ConfigurationManager.AppSettings["CupMerchantNo"]; }
  14. }
  15. static public string GetMerchantName
  16. {
  17. get { return ConfigurationManager.AppSettings["CupMerchantName"]; }
  18. }
  19. static public string GetPublicKey
  20. {
  21. get { return ConfigurationManager.AppSettings["CupPublicKey"]; }
  22. }
  23. static public string GetPrivateKey
  24. {
  25. get { return ConfigurationManager.AppSettings["CupPrivateKey"]; }
  26. }
  27. static public string GetPublicKeyPem
  28. {
  29. get { return ConfigurationManager.AppSettings["CupPublicKeyPem"]; }
  30. }
  31. static public string GetPrivateKeyPem
  32. {
  33. get { return ConfigurationManager.AppSettings["CupPrivateKeyPem"]; }
  34. }
  35. }
  36. }
  1. <appSettings>
  2. <add key="CupServerUrl" value=""/>
  3. <add key="CupMerchantNo" value=""/>
  4. <add key="CupMerchantName" value=""/>
  5. <add key="CupPublicKey" value=""/>
  6. <add key="CupPrivateKey" value=""/>
  7. <add key="CupPublicKeyPem" value="rsa_public_key.pem"/>
  8. <add key="CupPrivateKeyPem" value="rsa_private_key.pem"/>
  9.  
  10. </appSettings>
  1. [TestClass]
  2. public class RSATest
  3. {
  4. string serverUrl = AppConfig.GetServerUrl;
  5. string merchantNo = AppConfig.GetMerchantNo;
  6. //string publicKey = AppConfig.GetPublicKey;
  7. //string privateKey = AppConfig.GetPrivateKey;
  8.  
  9. private string content = "";
  10.  
  11. [TestMethod]
  12. public void TestMethod1()
  13. {
  14. string temp = AppDomain.CurrentDomain.BaseDirectory.Replace("bin\\Debug", "");
  15. string publicKeyPem = Path.Combine(temp, AppConfig.GetPublicKeyPem);
  16. string privateKeyPem = Path.Combine(temp, AppConfig.GetPrivateKeyPem);
  17.  
  18. string publicKey = Client.GetKeyFromPem("RSA PUBLIC KEY", publicKeyPem);
  19. string privateKey = Client.GetKeyFromPem("RSA PRIVATE KEY", privateKeyPem);
  20.  
  21. Client client = new Client(serverUrl, merchantNo, privateKey, publicKey);
  22.  
  23. var a = string.Format("待签名字符串:{0}", content);
  24.  
  25. string res = client.Sign(content);
  26.  
  27. var b = string.Format("签名结果:{0}", res);
  28.  
  29. bool ss = client.Verify(content, res);
  30.  
  31. var c = string.Format("验签结果:{0}", ss);
  32. }
  33. }

.Net C# RSA签名和验签重写的更多相关文章

  1. Delphi RSA签名与验签【支持SHA1WithRSA(RSA1)、SHA256WithRSA(RSA2)和MD5WithRSA签名与验签】

    作者QQ:(648437169) 点击下载➨ RSA签名与验签 [delphi RSA签名与验签]支持3种方式签名与验签(SHA1WithRSA(RSA1).SHA256WithRSA(RSA2)和M ...

  2. erlang的RSA签名与验签

    1.RSA介绍 RSA是目前最有影响力的公钥加密算法,该算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对 其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥,即公钥,而 ...

  3. .Net C# RSA签名和验签

    帮助类 using System; using System.Text; using System.IO; using System.Security.Cryptography; namespace ...

  4. java/php/c#版rsa签名以及验签实现

    本文为转载,请转载请注明地址: 原文地址为        http://xw-z1985.iteye.com/blog/1837376 在开放平台领域,需要给isv提供sdk,签名是Sdk中需要提供的 ...

  5. .NET Core RSA 签名和验签(密钥为 16 进制编码)

    使用 OpenSSL 生成公私钥对,命令: $ openssl genrsa -out rsa_1024_priv.pem $ openssl pkcs8 -topk8 -inform PEM -in ...

  6. RSA签名、验签、加密、解密

    最近在做一个项目,与一个支付渠道进行连接进行充值,为了安全,每个接口访问时,都要先登陆(调用登陆接口),拿到一个sessionKey,后续业务接口内容用它来进行3DES加密处理.而登陆需要用到RSA进 ...

  7. RSA签名和验签Util

    目录 1.DigitalSign类 2.CryptException异常类 3.加签示例 1.DigitalSign类 import org.apache.commons.codec.binary.B ...

  8. .NET RSA解密、签名、验签

    using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Sec ...

  9. Delphi支付宝支付【支持SHA1WithRSA(RSA)和SHA256WithRSA(RSA2)签名与验签】

    作者QQ:(648437169) 点击下载➨Delphi支付宝支付             支付宝支付api文档 [Delphi支付宝支付]支持条码支付.扫码支付.交易查询.交易退款.退款查询.交易撤 ...

随机推荐

  1. Java并发指南14:Java并发容器ConcurrentSkipListMap与CopyOnWriteArrayList

    原文出处http://cmsblogs.com/ 『chenssy』 到目前为止,我们在Java世界里看到了两种实现key-value的数据结构:Hash.TreeMap,这两种数据结构各自都有着优缺 ...

  2. Maven的几种新建项目方式

    1. 使用原型创建Maven的java工程 (1) 选择 JDK 的版本,勾选“使用原型创建”,选中 maven-archetype-quickstart,下一步. (2) 填写公司名,填写项目名,修 ...

  3. 修改oracle用户登录密码

    运行sqlplus进入输入密码界面 用户名输入: connect as sysdba 密码:这边乱输就可以了 然后进行输入下面的命令: 修改密码命令 alter user system identif ...

  4. SpringBoot保存数据报错:could not execute statement; SQL [n/a]; constraint [PRIMARY];nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

    使用SpringBoot做JAVA开发时,用Repository.save();保存数据的时候遇到了报错: could not execute statement; SQL [n/a]; constr ...

  5. 《maven实战》笔记(2)----一个简单maven项目的搭建,测试和打包

    参照<maven实战>在本地创建对应的基本项目helloworld,在本地完成后项目结构如下: 可以看到maven项目的骨架:src/main/java(javaz主代码)src/test ...

  6. jack语言编译器的实现过程

    目录: 1, 背景介绍

  7. Day04:循环结构(while、do-while、for)

    Java 循环结构 - while ,do...while,for 反复执行一段相同或相似代码的格式. 顺序结构的程序语句只能被执行一次.如果您想要同样的操作执行多次,,就需要使用循环结构. Java ...

  8. jdbc访问oracle超慢,但是PLSQL访问正常

    oracle数据库连接非常慢,sqlplus很快,用客户端就很慢,十几秒才好.然后服务器内存一下就飙升到了90%,最开始以为是表空间占满了,数据库连接数占满了.折腾了半天,重启,还是很慢.应用连接数据 ...

  9. Charles系列三:Charles打断点(包含修改请求,修改返回的内容),模拟慢速网络(弱网测试),域名映射,过滤请求,接口调试,打压测试

    一:Charles断点的使用(包含修改请求,修改返回的数据) 设置断点来修改请求和返回的数据,在开发过程中可以模拟多种响应.步骤如下: 1.添加断点方法有两种: 方法1:找到Charles中菜单项Pr ...

  10. Memcache分布式锁

    在分布式缓存的应用中,会遇到多个客户端同时争用的问题.这个时候,需要用到分布式锁,得到锁的客户端才有操作权限 下面通过一个简单例子介绍: 这里引用的是Memcached.ClientLibrary.d ...