众签demo

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Security.Cryptography;
  8. using System.IO;
  9. using System.Net.NetworkInformation;
  10. using System.Xml;
  11. using System.Net;
  12. using System.Text.RegularExpressions;
  13. using System.Net.Security;
  14. using System.IO.Compression;
  15.  
  16. namespace ConsoleApp1
  17. {
  18. class Program
  19. {
  20. static string private_key = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANIwqMKRiZMTMerWYJsp54AoMUcIbgZsdB4FjtGAzabh/NYH9ptNgNBfBo78yShPCP5c0wB0MVqg3wv5ExQRcCA5uj1ajO+FuHy5ESxmDDftxOzQlpHlMdvxCLZwJjy0+Il2AsZcbcSy3HMDN8HGhOG01A9rllbx6JnyC8hFdd+7AgMBAAECgYBztZHRuqjPrGt4ahe4k3L73CR0hDF9m8q4lDqxHoUX76RudufNSvc0vnsvz/01EX1T+em2gECDMbhYMP/NtmPQegoVIsojSGSSF8Q+q7JOCQlDi9JXiRMkoj+uSMeSqa4EbqOdoFAj+F8BlzYJCUCdfdcJRR4Zb8seFNlpUfDToQJBAPMGQt8dWfFGDGlo9Tnif5GIlz09Of7odn/NOyFb6c+fca0ufrg816GWGgLBl0qnj8bO/93P+EY0MWsVF8RytRkCQQDdaZtWGm9YImGT+PKdKapQvt0C5RAfi2OAnRndqCs8bA1K1kPII8hg/t2QFPshx48pqayJ7ve5/dmeig1y0eHzAkAKWnHu32k9hiZxNy97T9LveEo5KaqW2YBy4WNrgGbtmXVWU2zCnJTzJVnmVCkF3S2a4qaz5HBHTWHtlfB1Rg3BAkEA0cpr3fTkRX0mOf/rWhENiL6gSUrjsQ/w8v9ob8cVWIYFPkCxLuUAyy8Snp/SqFofA1n62yMrZPbriTXDsmS+EwJBAOFhYJS/x04TKX3H4iGDXLKLTSaQWoDyHBIZG61HSLVI8UTTre/Efc8jrs6GnYXkXAA0KeAcUQDxdeF0YRFhc2g=";
  21. static string zqid = "2FB987B8DCCBA679549";
  22. private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
  23. static void Main(string[] args)
  24. {
  25. IDictionary<string, string> paramsMap = new Dictionary<string, string>();
  26. paramsMap.Add("zqid", zqid);//唯一标示
  27. paramsMap.Add("signer", "");//用户唯一标示
  28. paramsMap.Add("contract_num", "NET-C003"); //合同编号
  29. paramsMap.Add("return_url", "test");//回调函地址
  30. paramsMap.Add("notify_url", "test");//回调函地址
  31. String context = GetSignContent(paramsMap);
  32. Console.WriteLine("context:{0}", context);
  33. string ws_sign_val = sign(context, private_key);
  34. Console.WriteLine("ws_sign_val:{0}", ws_sign_val);
  35. string url = "http://117.78.52.103/signAutomatic";
  36. HttpWebResponse res = (HttpWebResponse)CreatePostHttpResponse(url, paramsMap, , null, Encoding.UTF8, new CookieCollection());
  37.  
  38. string result = string.Empty;
  39.  
  40. using (System.IO.StreamReader reader = new System.IO.StreamReader(res.GetResponseStream()))
  41. {
  42. result = reader.ReadToEnd();
  43. reader.Close();
  44.  
  45. }
  46.  
  47. Console.WriteLine("result:{0}", result);
  48. Console.ReadKey();
  49. }
  50.  
  51. public static string GetSignContent(IDictionary<string, string> parameters)
  52. {
  53. IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
  54. IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
  55.  
  56. // 第二步:把所有参数名和参数值串在一起
  57. StringBuilder query = new StringBuilder("");
  58. while (dem.MoveNext())
  59. {
  60. string key = dem.Current.Key;
  61. string value = dem.Current.Value;
  62. if (!string.IsNullOrEmpty(key))
  63. {
  64. query.Append(key).Append("=").Append(value).Append("&");
  65. }
  66. }
  67. string content = query.ToString().Substring(, query.Length - );
  68.  
  69. return content;
  70. }
  71.  
  72. public static string sign(string content, string privateKey)
  73. {
  74.  
  75. byte[] Data = Encoding.UTF8.GetBytes(content);
  76.  
  77. RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
  78.  
  79. SHA1 sh = new SHA1CryptoServiceProvider();
  80.  
  81. byte[] signData = rsa.SignData(Data, sh);
  82.  
  83. return Convert.ToBase64String(signData);
  84.  
  85. }
  86.  
  87. private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr)
  88. {
  89.  
  90. byte[] pkcs8privatekey;
  91.  
  92. pkcs8privatekey = Convert.FromBase64String(pemstr);
  93.  
  94. if (pkcs8privatekey != null)
  95. {
  96.  
  97. RSACryptoServiceProvider rsa = DecodePrivateKeyInfo(pkcs8privatekey);
  98.  
  99. return rsa;
  100.  
  101. }
  102.  
  103. else
  104.  
  105. return null;
  106.  
  107. }
  108.  
  109. private static RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8)
  110. {
  111.  
  112. byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
  113.  
  114. byte[] seq = new byte[];
  115.  
  116. MemoryStream mem = new MemoryStream(pkcs8);
  117.  
  118. int lenstream = (int)mem.Length;
  119.  
  120. BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
  121.  
  122. byte bt = ;
  123.  
  124. ushort twobytes = ;
  125.  
  126. try
  127. {
  128.  
  129. twobytes = binr.ReadUInt16();
  130.  
  131. if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
  132.  
  133. binr.ReadByte(); //advance 1 byte
  134.  
  135. else if (twobytes == 0x8230)
  136.  
  137. binr.ReadInt16(); //advance 2 bytes
  138.  
  139. else
  140.  
  141. return null;
  142.  
  143. bt = binr.ReadByte();
  144.  
  145. if (bt != 0x02)
  146.  
  147. return null;
  148.  
  149. twobytes = binr.ReadUInt16();
  150.  
  151. if (twobytes != 0x0001)
  152.  
  153. return null;
  154.  
  155. seq = binr.ReadBytes(); //read the Sequence OID
  156.  
  157. if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
  158.  
  159. return null;
  160.  
  161. bt = binr.ReadByte();
  162.  
  163. if (bt != 0x04) //expect an Octet string
  164.  
  165. return null;
  166.  
  167. bt = binr.ReadByte(); //read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count
  168.  
  169. if (bt == 0x81)
  170.  
  171. binr.ReadByte();
  172.  
  173. else
  174.  
  175. if (bt == 0x82)
  176.  
  177. binr.ReadUInt16();
  178.  
  179. //------ at this stage, the remaining sequence should be the RSA private key
  180.  
  181. byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position));
  182.  
  183. RSACryptoServiceProvider rsacsp = DecodeRSAPrivateKey(rsaprivkey);
  184.  
  185. return rsacsp;
  186.  
  187. }
  188.  
  189. catch (Exception)
  190. {
  191.  
  192. return null;
  193.  
  194. }
  195.  
  196. finally { binr.Close(); }
  197.  
  198. }
  199.  
  200. private static bool CompareBytearrays(byte[] a, byte[] b)
  201. {
  202.  
  203. if (a.Length != b.Length)
  204.  
  205. return false;
  206.  
  207. int i = ;
  208.  
  209. foreach (byte c in a)
  210. {
  211.  
  212. if (c != b[i])
  213.  
  214. return false;
  215.  
  216. i++;
  217.  
  218. }
  219.  
  220. return true;
  221.  
  222. }
  223.  
  224. public static WebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
  225. {
  226. if (string.IsNullOrEmpty(url))
  227. {
  228. throw new ArgumentNullException("url");
  229. }
  230. if (requestEncoding == null)
  231. {
  232. throw new ArgumentNullException("requestEncoding");
  233. }
  234. HttpWebRequest request = null;
  235. //如果是发送HTTPS请求
  236. if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
  237. {
  238. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  239. request = WebRequest.Create(url) as HttpWebRequest;
  240. request.ProtocolVersion = HttpVersion.Version10;
  241. }
  242. else
  243. {
  244. request = WebRequest.Create(url) as HttpWebRequest;
  245. }
  246. request.Method = "POST";
  247. request.ContentType = "application/x-www-form-urlencoded";
  248.  
  249. if (!string.IsNullOrEmpty(userAgent))
  250. {
  251. request.UserAgent = userAgent;
  252. }
  253. else
  254. {
  255. request.UserAgent = DefaultUserAgent;
  256. }
  257.  
  258. if (timeout.HasValue)
  259. {
  260. request.Timeout = timeout.Value;
  261. }
  262. if (cookies != null)
  263. {
  264. request.CookieContainer = new CookieContainer();
  265. request.CookieContainer.Add(cookies);
  266. }
  267. //如果需要POST数据
  268. if (!(parameters == null || parameters.Count == ))
  269. {
  270. StringBuilder buffer = new StringBuilder();
  271. int i = ;
  272. foreach (string key in parameters.Keys)
  273. {
  274. if (i > )
  275. {
  276. buffer.AppendFormat("&{0}={1}", key, parameters[key]);
  277. }
  278. else
  279. {
  280. buffer.AppendFormat("{0}={1}", key, parameters[key]);
  281. }
  282. i++;
  283. }
  284.  
  285. byte[] data = requestEncoding.GetBytes(buffer.ToString());
  286. using (Stream stream = request.GetRequestStream())
  287. {
  288. stream.Write(data, , data.Length);
  289. stream.Close();
  290. }
  291. ;
  292. System.Console.Write(data.ToString() + "\n-----------");
  293. /* Stream myResponseStream = request.GetResponse().GetResponseStream();
  294. StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
  295. string retString = myStreamReader.ReadToEnd();
  296. System.Console.Write(retString);*/
  297. //HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  298. /* string result = string.Empty;
  299.  
  300. using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream()))
  301. {
  302. result = reader.ReadToEnd();
  303.  
  304. System.Console.Write(result+"\n");
  305. }*/
  306. }
  307. return (HttpWebResponse)request.GetResponse();
  308. }
  309.  
  310. private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
  311. {
  312.  
  313. byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;
  314.  
  315. // --------- Set up stream to decode the asn.1 encoded RSA private key ------
  316.  
  317. MemoryStream mem = new MemoryStream(privkey);
  318.  
  319. BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
  320.  
  321. byte bt = ;
  322.  
  323. ushort twobytes = ;
  324.  
  325. int elems = ;
  326.  
  327. try
  328. {
  329.  
  330. twobytes = binr.ReadUInt16();
  331.  
  332. if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
  333.  
  334. binr.ReadByte(); //advance 1 byte
  335.  
  336. else if (twobytes == 0x8230)
  337.  
  338. binr.ReadInt16(); //advance 2 bytes
  339.  
  340. else
  341.  
  342. return null;
  343.  
  344. twobytes = binr.ReadUInt16();
  345.  
  346. if (twobytes != 0x0102) //version number
  347.  
  348. return null;
  349.  
  350. bt = binr.ReadByte();
  351.  
  352. if (bt != 0x00)
  353.  
  354. return null;
  355.  
  356. //------ all private key components are Integer sequences ----
  357.  
  358. elems = GetIntegerSize(binr);
  359.  
  360. MODULUS = binr.ReadBytes(elems);
  361.  
  362. elems = GetIntegerSize(binr);
  363.  
  364. E = binr.ReadBytes(elems);
  365.  
  366. elems = GetIntegerSize(binr);
  367.  
  368. D = binr.ReadBytes(elems);
  369.  
  370. elems = GetIntegerSize(binr);
  371.  
  372. P = binr.ReadBytes(elems);
  373.  
  374. elems = GetIntegerSize(binr);
  375.  
  376. Q = binr.ReadBytes(elems);
  377.  
  378. elems = GetIntegerSize(binr);
  379.  
  380. DP = binr.ReadBytes(elems);
  381.  
  382. elems = GetIntegerSize(binr);
  383.  
  384. DQ = binr.ReadBytes(elems);
  385.  
  386. elems = GetIntegerSize(binr);
  387.  
  388. IQ = binr.ReadBytes(elems);
  389.  
  390. // ------- create RSACryptoServiceProvider instance and initialize with public key -----
  391.  
  392. RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
  393.  
  394. RSAParameters RSAparams = new RSAParameters();
  395.  
  396. RSAparams.Modulus = MODULUS;
  397.  
  398. RSAparams.Exponent = E;
  399.  
  400. RSAparams.D = D;
  401.  
  402. RSAparams.P = P;
  403.  
  404. RSAparams.Q = Q;
  405.  
  406. RSAparams.DP = DP;
  407.  
  408. RSAparams.DQ = DQ;
  409.  
  410. RSAparams.InverseQ = IQ;
  411.  
  412. RSA.ImportParameters(RSAparams);
  413.  
  414. return RSA;
  415.  
  416. }
  417.  
  418. catch (Exception)
  419. {
  420.  
  421. return null;
  422.  
  423. }
  424.  
  425. finally { binr.Close(); }
  426.  
  427. }
  428.  
  429. private static int GetIntegerSize(BinaryReader binr)
  430. {
  431. byte bt = ;
  432. byte lowbyte = 0x00;
  433. byte highbyte = 0x00;
  434. int count = ;
  435. bt = binr.ReadByte();
  436. if (bt != 0x02) //expect integer
  437. return ;
  438. bt = binr.ReadByte();
  439.  
  440. if (bt == 0x81)
  441. count = binr.ReadByte(); // data size in next byte
  442. else
  443. if (bt == 0x82)
  444. {
  445. highbyte = binr.ReadByte(); // data size in next 2 bytes
  446. lowbyte = binr.ReadByte();
  447. byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
  448. count = BitConverter.ToInt32(modint, );
  449. }
  450. else
  451. {
  452. count = bt; // we already have the data size
  453. }
  454.  
  455. while (binr.ReadByte() == 0x00)
  456. { //remove high order zeros in data
  457. count -= ;
  458. }
  459. binr.BaseStream.Seek(-, SeekOrigin.Current); //last ReadByte wasn't a removed zero, so back up a byte
  460. return count;
  461. }
  462.  
  463. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  464. {
  465. return true; //总是接受
  466. }
  467. }
  468. }

众签demo的更多相关文章

  1. 速卖通AE平台+聚石塔+奇门 完整教程V2

    公司是跨境电商,在阿里马马的速卖通平台上开有店铺,并且基于速卖通开放平台,自主研发了ERP系统,居今已有3年多的时间了,一直很稳定. 今年初,速卖通AE开放平台改版,并入淘宝开放平台中,我们的麻烦就开 ...

  2. AI学习---分类算法[K-近邻 + 朴素贝叶斯 + 决策树 + 随机森林 ]

    分类算法:对目标值进行分类的算法    1.sklearn转换器(特征工程)和预估器(机器学习)    2.KNN算法(根据邻居确定类别 + 欧氏距离 + k的确定),时间复杂度高,适合小数据    ...

  3. NodeJs支付宝移动支付签名及验签

    非常感谢 :http://www.jianshu.com/p/8513e995ff3a?utm_campaign=hugo&utm_medium=reader_share&utm_co ...

  4. ASP.NET MVC搭建项目后台UI框架—4、tab多页签支持

    目录 ASP.NET MVC搭建项目后台UI框架—1.后台主框架 ASP.NET MVC搭建项目后台UI框架—2.菜单特效 ASP.NET MVC搭建项目后台UI框架—3.面板折叠和展开 ASP.NE ...

  5. ASP.NET MVC搭建项目后台UI框架—5、Demo演示Controller和View的交互

    目录 ASP.NET MVC搭建项目后台UI框架—1.后台主框架 ASP.NET MVC搭建项目后台UI框架—2.菜单特效 ASP.NET MVC搭建项目后台UI框架—3.面板折叠和展开 ASP.NE ...

  6. 支付宝App支付签名和验签

    代码: using CMS.Utility.ReturnResult; using OAuthWebAPI.Package; using Common; using System; using Sys ...

  7. 《众妙之门——精通CSS3》一书知识点剖析

    不得不佩服京东的速度,昨天刚下单的两本书今天上午就到了.其中一本是全彩页的<众妙之门 - 精通CSS3>,细看了前几十页,书上的叙述方式给我的印象其实不如“彩页”来的讨喜——接连说上几个例 ...

  8. iOS下使用SHA1WithRSA算法加签源码

    首先了解一下几个相关概念,以方便后面遇到的问题的解决: RSA算法:1977年由Ron Rivest.Adi Shamirh和LenAdleman发明的,RSA就是取自他们三个人的名字.算法基于一个数 ...

  9. LinbDesk --- 新的extjs4.2 desktop demo : 技术交流Q群:336584192

    很多朋友对extjs desktop感兴趣,就在原来简单的dsktop基础上,作了很多拓展  主要例如以下: 软件更新情况介绍: LinbDesk 拓展自Extjs 4.2的桌面Demo 拓展代码适用 ...

随机推荐

  1. P3293 [SCOI2016]美味

    题目描述 一家餐厅有 n 道菜,编号 1...n ,大家对第 i 道菜的评价值为 ai(1<=i<=n).有 m 位顾客,第 i 位顾客的期望值为 bi,而他的偏好值为 xi .因此,第 ...

  2. 锁对象-Lock: 同步问题更完美的处理方式 (ReentrantReadWriteLock读写锁的使用/源码分析)

    Lock是java.util.concurrent.locks包下的接口,Lock 实现提供了比使用synchronized 方法和语句可获得的更广泛的锁定操作,它能以更优雅的方式处理线程同步问题,我 ...

  3. hbase 分页过滤(新老API的差别)

    在hbase2.0以前分页过滤必须以上一次的最后一行+空字节数组作为下一次的起始行, 因为scan扫描的时候是包含起始行的,为了既能准确定位起始行,但又不重复把上一次的最末一行加入下一页, 所以,权威 ...

  4. Spring Security OAuth 个性化token

    个性化Token 目的 默认通过调用 /oauth/token 返回的报文格式包含以下参数 { "access_token": "e6669cdf-b6cd-43fe-a ...

  5. 一种KEIL中定义过的变量在使用中提示未定义的情况

    [环境] > KEIL5.25 > win10 > @2018-4-23 [问题] 头文件互包含导致的错误(使用了另一文件的类型定义) 文件<fileA.h> <f ...

  6. 《Linux内核设计与实现》学习总结 Chap18

    一.准备开始 1.一个确定的bug,但大部分bug通常都不是行为可靠且定义明确的. 2.一个藏匿bug的内核版本. 3.相关内核代码的知识和运气. 二.内核中的bug 1.bug的表象: 明白无误的错 ...

  7. java 批量文件后缀重命名

    import java.io.File; public class BatchFileSuffixRename { public static void main(String[] args) { / ...

  8. 【cdq分治】【P4390】[BOI2007]Mokia 摩基亚

    Description 给你一个 \(W~\times~W\) 的矩阵,每个点有权值,每次进行单点修改或者求某子矩阵内权值和,允许离线 Input 第一行是两个数字 \(0\) 和矩阵大小 \(W\) ...

  9. configServer的高可用

    1.利用RabbitMQ或者是Kafka来搭建集群. 2.利用nginx来进行 3.利用Eureka来搭建

  10. SSH框架搭建问题总结

    1.eclipse中tomcat配置是否正确?能否在网页中访问的到? 如何在eclipse中配置tomcat就不说了,我们看下问题,在网页上访问tomcat的地址,为什么出现404错误呢? 解决办法: ...