废话少说,直接上代码(⊙﹏⊙)
class Program { //签名证书 public static X509Certificate2 cerSigneCert; private static char[] hexChars; public Program() { cerSigneCert = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + @"resources016100001118204.p12",""); } static voID Main(string[] args) { string xml = "xml字符串 <SIGNED_MSG />"; string newXML = SHA1withRSA(xml); string url = "访问地址"; string requestUrl = RequestUrl(url,newXML); } /// <summary> /// 签名 /// PS:(SIGNED_MSG是属性的名称) /// </summary> /// <param name="xml"></param> /// <returns></returns> private static string SHA1withRSA(string xml) { string oldXML = xml.Replace("<SIGNED_MSG />",""); SHA1CryptoServiceProvIDer sha1 = new SHA1CryptoServiceProvIDer(); byte[] msg = sha1.ComputeHash(EnCoding.GetEnCoding("GBK").GetBytes(oldXML)); RSAPKCS1SignatureFormatter signe = new RSAPKCS1SignatureFormatter(); signe.SetKey(cerSigneCert.PrivateKey);//设置用于签名的私钥 signe.SetHashAlgorithm("SHA1"); var signeText = ToHex(signe.CreateSignature(msg));//创建签名 string newXML = xml.Replace("<SIGNED_MSG />","<SIGNED_MSG>" + signeText + "</SIGNED_MSG>"); return newXML; } private static string ToHex(byte[] ba) { if (ba == null) return ""; char[] buf = new char[ba.Length * 2]; int p = 0; foreach (byte b in ba) { buf[p++] = hexChars[b >> 4]; buf[p++] = hexChars[b & 0x0f]; } return new string(buf); } /// <summary> /// 发送请求,获取响应 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <returns></returns> public static string RequestUrl(string url,string data)//发送方法 { var request = WebRequest.Create(url) as httpWebRequest; request.ProtocolVersion = httpVersion.Version11; // 这里设置了协议类型。 request.KeepAlive = false; ServicePointManager.ServerCertificateValIDationCallback = new RemoteCertificateValIDationCallback(RemoteCertificateValIDate); ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionlimit = 100; ServicePointManager.Expect100Continue = false; request.Method = "post"; request.ContentType = "text/xml"; request.headers.Add("charset:gbk"); var enCoding = EnCoding.GetEnCoding("GBK"); if (data != null) { byte[] buffer = enCoding.GetBytes(data); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer,0,buffer.Length); } else { } using (httpWebResponse wr = request.GetResponse() as httpWebResponse) { using (StreamReader reader = new StreamReader(wr.GetResponseStream(),enCoding)) { string strResult = reader.ReadToEnd(); return strResult; } } } private static bool RemoteCertificateValIDate(object sender,X509Certificate cert,X509Chain chain,SslPolicyErrors error) { System.Console.Writeline("Warning,trust any certificate"); //为了通过证书验证,总是返回true return true; } }
有关XML转换,大家请参考上一篇文章: https://www.cnblogs.com/shuai7boy/p/10963734.html
总结以上是内存溢出为你收集整理的带"签名"的请求接口实现全部内容,希望文章能够帮你解决带"签名"的请求接口实现所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)