C#与java TCP通道加密通信实例
1、背景说明
公司收费系统需要与银行做实时代收对接,业务协议使用我们收费系统的标准。但是银行要求在业务协议的基础上,使用银行的加密规则。
- 采用
md5
计算报文摘要,保证数据的完整性 - 采用
rsa256
对摘要进行签名,保证报文的合法性 - 采用
aes
进行对称加密,保证报文的私密性
我们几个人一评估,在业务报文上加一套加密方案,加密方法又是通用的,这个能有什么问题,没问题。
2、测试证书
银行发来的测试证书在这里
后来才知道这应该叫java
版格式,而且这个证书经验证是正确的,可正常签名、验签的。
-----begin private key----- miievgibadanbgkqhkig9w0baqefaascbkgwggskageaaoibaqdllhc9gw7aiuv8 urnf8ptprjzww26oessta1ghtuqhdjcaosbxkwac2/sxv3lsurizfvy+hhvh6zgq ncwhsbnwd5ucq8zibkb29kibb9ovkftxpsmtfzdagxreupg1ce5zxlvpmsm8ggw9 2foq/cgygbingzascyr5mmmgh5pwievh7milos5fmx9hwdukazgdxjazhb5ul8uu vb83iytkjiems346x41jcm8uqwl4hrapvtougsiz+oidpotpfjqtjvzp1p/bvlqs rjhsn1a5ado+ygh231+pkdfkzhwxddmei3yy2zxqjkthpvc033o2yfvn5tlq79p0 j/hswy0fagmbaaecggebakzkkwjhfcf4w+91gsw+uxip2fuy4mgl0zkoqa6j6dpw qpwu2bwj66tladbxikzxeu/bu4zgqaslfhhtjxie4b4qffflhhrikyyd8bwjzy+/ kdyhepmug7louu5jxxtvdjob4vpvlluoaqnmlp0jcto++e2zmuwy/xf/jbbfahsa tsm3phyn/zltmdyfqfdc6ig+ikejw0dnnbqzpfytijpygw3qs6xkkndroq0v1vpj occumlfe8tottgobt1q8qrnkxfb9dyxxkgx/qgdfv8a+kwv1wuwyqgose9gu0l28 twgofhs399ojffjdwa/o2no+kcakjjl5dcijzldm8qecgyea/t4jgs32js8cxyek hh0tgozhvsh/f2ioi1+patbkcqan34n/ncbueyn8ep/k95a+bpmiltaouzykbtgf bvsqdkcyg19qsv5b2ldyfvbospwss7olcv78euplbclcpyfmbq/medytysjsjkrc ror0p30cu/vep72wtyy4zmy6yp8cgyea5ptkmdaud48hli7gnwkkiveh16cg+0fs a1jgrbuzhoovtuk8xmuxsgyyeyyolxd7i5q4vdzwtzjgkazcmthzhmusbzt6i04o rdkfb3hexgoiigvchh+cjyohc6aqkd3vfowvyqz0s5slc7ef4qwy9zwd3hwwgfee xko1zc/mryecgyanq2ubg7d2/5bgi0iaqv/w1pjrjb/kejzjdsb+0qmv5th8ic+h qram4hkxosbmtmluxxix1n2cmrxl3wkvm20kmn70hul/dloj1srashsd49bwy1mx yotkdale2motuyolzih41u2k03c0/l/ahixhi2npind/p7dfh+kuavehawkbga2i c3o26amujspwtour3gjujqes0syt7fvmakxw+kbpxgxatgu+jupbnr98lgkfd+sa oevtt8eoz2iwtvzqgv/7sleqx+io744b1axvytzr9go9gk9sthel9n+y+kd2tl8f k6/o0o5xxmnjsjs40kxe3ny8y7ema0gc65pl9zebaogbanpd8fp04tttyqiune8g jroiqgtcuoenp4gjv5vvgus19qvf6rvmr1yemlojxgujcaqjte878zep6ur2wezu veqoqqxrlwkbtawya0iabhudd/nah5ccjbfcyrfdnqonnrbji5accbful6fehkof xquoc1mnaukccb1acvtbrngi -----end private key----- -----begin public key----- miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqea5zyxpymo2ilr/fez3/d7 t0swcmnujnkre2trh7bqh3ywmqlavylmgtv0svd5bfeysxvwph4bx+s4kjqloum5 8hebnkvgygzg9vzcg2/afsn7cabde32xqif0xld4nxboc8s76zkjpiimpdnzqvwo gig4p4mwengeetjjib+t8cbfyezipaeuxzmfr1g7iggyhv42mrwevc/lrr2/n4sr sisbjkt+ol+nywjpfemc+iuwj77alhkim/qig6alt3yulsvcz9t/275ulesr0p9w uwg6psob9t9fjynxys4cmqwzhin2mts8aisrr6vxnn9ztsn75+u5uo/t9i/4bmgn hwidaqab -----end public key-----
c#
版本证书在这里,这个是后来正确的测试证书转换的c#
版本,与上面的java
版本对应
私钥
<rsakeyvalue><modulus>5zyxpymo2ilr/fez3/d7t0swcmnujnkre2trh7bqh3ywmqlavylmgtv0svd5bfeysxvwph4bx+s4kjqloum58hebnkvgygzg9vzcg2/afsn7cabde32xqif0xld4nxboc8s76zkjpiimpdnzqvwogig4p4mwengeetjjib+t8cbfyezipaeuxzmfr1g7iggyhv42mrwevc/lrr2/n4srsisbjkt+ol+nywjpfemc+iuwj77alhkim/qig6alt3yulsvcz9t/275ulesr0p9wuwg6psob9t9fjynxys4cmqwzhin2mts8aisrr6vxnn9ztsn75+u5uo/t9i/4bmgnhw==</modulus><exponent>aqab</exponent><p>/t4jgs32js8cxyekhh0tgozhvsh/f2ioi1+patbkcqan34n/ncbueyn8ep/k95a+bpmiltaouzykbtgfbvsqdkcyg19qsv5b2ldyfvbospwss7olcv78euplbclcpyfmbq/medytysjsjkrcror0p30cu/vep72wtyy4zmy6yp8=</p><q>5ptkmdaud48hli7gnwkkiveh16cg+0fsa1jgrbuzhoovtuk8xmuxsgyyeyyolxd7i5q4vdzwtzjgkazcmthzhmusbzt6i04ordkfb3hexgoiigvchh+cjyohc6aqkd3vfowvyqz0s5slc7ef4qwy9zwd3hwwgfeexko1zc/mrye=</q><dp>datlaruw9v+w4itcgqlf8ntyayqfyno843bg/tkjfebyfchpouewpubyl6egzrtc1f8yl9z9gpq15d1pfzttjjje9b7i/w5ai9bk2kounepqcgntf8qlzhwpxtjdrvmjpc4h+nbtitnwtp5fwiysr4tp6sdxfz+w3x/irgfrb2s=</dp><dq>dyhzejbpoy6ni/c2i6vcylqlb6zrlk3svuwctfb4oe/ebfq2bt4lsls1h3ywcr935icgs9o3x45nalc2/ncbx/tit6pf6kjvjhvudfxk1lh0aj0yr1joeqv2f5j6r3a0vx+tr87q7nfey0mynljqpctedjxjt6ydqzzrmkv1kqe=</dq><inverseq>093wu/ti1o3kqk6ctwyms4haa0jsgsenialxlvua6zx2pv/qtuyvvgqywipgc6nxpam0tzvxl6nq6vzz5m5ura6qpdevaofnpzgdsjpufqn3+cchlwkmf9xit92dcic2semlkbxxt9sxousgsgvdbshzwadq4pwihuak+0fe0yg=</inverseq><d>pkqramd9wxhb73uaxb65ei/yw7liacxrko5adonp09zcnc7yhanrq0samfeipnes79u7jocobkuwgfopegthvhauuwwggsgrlipwhalnl78p1gcq8xqbsuhrtmnddo90k5vi8+8su44cqeys/smjm7757bmy5zj9d/+mft9oexq1izc8dg3/ovmwpiwp8nzqkd6ip6nbr2c0fbmkxk2kolibbdblpcqscnghdrxw+mogijqyv97y2i20agg3vdyqs0revv13jdeqbh9can+/wd6ra/va7bhaaix70a7qvbxnyy58dlf32gl98l3br+jaej4ojoqomvl0iipmsobxaq==</d></rsakeyvalue> 公钥
<rsakeyvalue><modulus>5zyxpymo2ilr/fez3/d7t0swcmnujnkre2trh7bqh3ywmqlavylmgtv0svd5bfeysxvwph4bx+s4kjqloum58hebnkvgygzg9vzcg2/afsn7cabde32xqif0xld4nxboc8s76zkjpiimpdnzqvwogig4p4mwengeetjjib+t8cbfyezipaeuxzmfr1g7iggyhv42mrwevc/lrr2/n4srsisbjkt+ol+nywjpfemc+iuwj77alhkim/qig6alt3yulsvcz9t/275ulesr0p9wuwg6psob9t9fjynxys4cmqwzhin2mts8aisrr6vxnn9ztsn75+u5uo/t9i/4bmgnhw==</modulus><exponent>aqab</exponent></rsakeyvalue>
3、复制粘贴加密算法
百度c#rsa
签名,大差不差,还简洁明了,很快签名、验签方法就出来啦。
/// <summary> /// rsa签名 /// </summary> /// <param name="privatekey">私钥</param> /// <param name="data">待签名的内容</param> /// <returns></returns> public static string rsasigncsharp(string data, string privatekey, string hashalgorithm = "sha256", string encoding = "utf-8") { rsacryptoserviceprovider rsa = new rsacryptoserviceprovider(); rsa.fromxmlstring(privatekey); //加载私钥 var databytes = encoding.getencoding(encoding).getbytes(data); var hashbytesignature = rsa.signdata(databytes, hashalgorithm); return convert.tobase64string(hashbytesignature); } /// <summary> /// 验证签名 /// </summary> /// <param name="data"></param> /// <param name="signature"></param> /// <param name="encoding"></param> /// <returns></returns> public static bool verifycsharp(string data, string publickey, string signature, string hashalgorithm = "sha256", string encoding = "utf-8") { rsacryptoserviceprovider rsa = new rsacryptoserviceprovider(); //导入公钥,准备验证签名 rsa.fromxmlstring(publickey); //返回数据验证结果 byte[] data = encoding.getencoding(encoding).getbytes(data); byte[] rgbsignature = convert.frombase64string(signature); return rsa.verifydata(data, hashalgorithm, rgbsignature); }
王婆卖瓜,自卖自夸。
来波自签自验吧,竟然不过。怎么就不过了呢,越简单越感觉无处下手调试呀。算法都封装了,那只可能是参数的问题了。
4、证书格式转换
主要原因是java
和c#
采用的公钥、私钥存储格式不一致,导致无法直接使用银行提供的java
版证书,需要进行格式转换,转换成c#
能够识别的证书。这里是转换方法
/// <summary> /// rsa公钥格式转换,java->.net /// </summary> /// <param name="publickey">java生成的公钥</param> /// <returns></returns> public static string rsapublickeyjava2dotnet(string publickey) { rsakeyparameters publickeyparam = (rsakeyparameters)publickeyfactory.createkey(convert.frombase64string(publickey)); return string.format("<rsakeyvalue><modulus>{0}</modulus><exponent>{1}</exponent></rsakeyvalue>", convert.tobase64string(publickeyparam.modulus.tobytearrayunsigned()), convert.tobase64string(publickeyparam.exponent.tobytearrayunsigned())); } /// <summary> /// rsa私钥格式转换,java->.net /// </summary> /// <param name="privatekey">java生成的私钥</param> /// <returns></returns> public static string rsaprivatekeyjava2dotnet(string privatekey) { rsaprivatecrtkeyparameters privatekeyparam = (rsaprivatecrtkeyparameters)privatekeyfactory.createkey(convert.frombase64string(privatekey)); return string.format("<rsakeyvalue><modulus>{0}</modulus><exponent>{1}</exponent><p>{2}</p><q>{3}</q><dp>{4}</dp><dq>{5}</dq><inverseq>{6}</inverseq><d>{7}</d></rsakeyvalue>", convert.tobase64string(privatekeyparam.modulus.tobytearrayunsigned()), convert.tobase64string(privatekeyparam.publicexponent.tobytearrayunsigned()), convert.tobase64string(privatekeyparam.p.tobytearrayunsigned()), convert.tobase64string(privatekeyparam.q.tobytearrayunsigned()), convert.tobase64string(privatekeyparam.dp.tobytearrayunsigned()), convert.tobase64string(privatekeyparam.dq.tobytearrayunsigned()), convert.tobase64string(privatekeyparam.qinv.tobytearrayunsigned()), convert.tobase64string(privatekeyparam.exponent.tobytearrayunsigned())); }
结果证书转换也不过,直接抛异常。然后就反复梳理代码逻辑,总觉得转换方法不对,各种百度。
众里寻他千百度。蓦然回首,那人却在,灯火阑珊处。
这大概就是这种比较不可思议问题的纠结吧,证书不会有错吧?
出于验证的目的我们找到了线上在用的正常证书,进行转换,正常转换,签名验签正常。不至于吧,我又找来了java
的转换方法。下面是java
代码,转换java
证书为c#
格式:
package com.company; import com.sun.org.apache.xerces.internal.impl.dv.util.base64; import java.security.keyfactory; import java.security.publickey; import java.security.interfaces.rsaprivatecrtkey; import java.security.interfaces.rsapublickey; import java.security.spec.pkcs8encodedkeyspec; import java.security.spec.x509encodedkeyspec; public class cerjava2csharp { public static void main(string[] args) { string tes="java版私钥证书"; byte[] temp=b64decode(tes); string ver=getrsaprivatekeyasnetformat(temp);//转换私钥 string tes1="java版公钥证书"; byte[] temp1=b64decode(tes1); string ver1=getrsapublickeyasnetformat(temp1);//转换公钥 string temp2= ver1; } public static string getrsaprivatekeyasnetformat(byte[] encodedprivkey) { try { stringbuffer buff = new stringbuffer(1024); pkcs8encodedkeyspec pvkkeyspec = new pkcs8encodedkeyspec( encodedprivkey); keyfactory keyfactory = keyfactory.getinstance("rsa"); rsaprivatecrtkey pvkkey = (rsaprivatecrtkey) keyfactory .generateprivate(pvkkeyspec); buff.append("<rsakeyvalue>"); buff.append("<modulus>" + b64encode(removemszero(pvkkey.getmodulus().tobytearray())) + "</modulus>"); buff.append("<exponent>" + b64encode(removemszero(pvkkey.getpublicexponent() .tobytearray())) + "</exponent>"); buff.append("<p>" + b64encode(removemszero(pvkkey.getprimep().tobytearray())) + "</p>"); buff.append("<q>" + b64encode(removemszero(pvkkey.getprimeq().tobytearray())) + "</q>"); buff.append("<dp>" + b64encode(removemszero(pvkkey.getprimeexponentp() .tobytearray())) + "</dp>"); buff.append("<dq>" + b64encode(removemszero(pvkkey.getprimeexponentq() .tobytearray())) + "</dq>"); buff.append("<inverseq>" + b64encode(removemszero(pvkkey.getcrtcoefficient() .tobytearray())) + "</inverseq>"); buff.append("<d>" + b64encode(removemszero(pvkkey.getprivateexponent() .tobytearray())) + "</d>"); buff.append("</rsakeyvalue>"); return buff.tostring().replaceall("[ \t\n\r]", ""); } catch (exception e) { system.err.println(e); return null; } } public static string getrsapublickeyasnetformat(byte[] encodedprivkey) { try { stringbuffer buff = new stringbuffer(1024); pkcs8encodedkeyspec pvkkeyspec = new pkcs8encodedkeyspec(encodedprivkey); keyfactory keyfactory = keyfactory.getinstance("rsa"); rsapublickey pukkey=(rsapublickey) keyfactory.generatepublic(new x509encodedkeyspec(encodedprivkey)); // rsaprivatecrtkey pvkkey = (rsaprivatecrtkey) keyfactory.generateprivate(pvkkeyspec); //publickey publickey =keyfactory.getinstance("rsa").generatepublic(pvkkeyspec); buff.append("<rsakeyvalue>"); buff.append("<modulus>" + b64encode(removemszero(pukkey.getmodulus().tobytearray())) + "</modulus>"); buff.append("<exponent>" + b64encode(removemszero(pukkey.getpublicexponent() .tobytearray())) + "</exponent>"); buff.append("</rsakeyvalue>"); return buff.tostring().replaceall("[ \t\n\r]", ""); } catch (exception e) { system.err.println(e); return null; } } public static string encodepublickeytoxml(publickey key) { if (!rsapublickey.class.isinstance(key)) { return null; } rsapublickey pubkey = (rsapublickey) key; stringbuilder sb = new stringbuilder(); sb.append("<rsakeyvalue>"); sb.append("<modulus>") .append(base64.encode(pubkey.getmodulus().tobytearray())) .append("</modulus>"); sb.append("<exponent>") .append(base64.encode(pubkey.getpublicexponent() .tobytearray())).append("</exponent>"); sb.append("</rsakeyvalue>"); return sb.tostring(); } public static byte[] removemszero(byte[] data) { byte[] data1; int len = data.length; if (data[0] == 0) { data1 = new byte[data.length - 1]; system.arraycopy(data, 1, data1, 0, len - 1); } else data1 = data; return data1; } public static string b64encode(byte[] data) { string b64str = new string(base64.encode(data)); return b64str; } public static byte[] b64decode(string data) { byte[] decodedata = base64.decode(data); return decodedata; } }
经验证,仍然无法转换,好吧,实锤了,证书有问题。至于是什么原因造成的证书问题,不太清楚。更换证书后,转换、签名、验签一切ok。
5、ps1 rsa证书格式
我们通常看到的比较多的证书对形式,pfx
证书包含了公钥信息和私钥信息。cer
证书只包含公钥信息。pfx证书既可以导出为pfx证书,也可以导出为cer
证书。pfx证书导出时,会提示是否导出私钥,导出私钥即pfx证书,不到出则是cer
证书。pfx证书导入、导出和程序加载时,是需要提供证书密码的。
-
私钥证书常见格式:
pfx p12 pem key
-
公钥证书常见格式:
pem crt/cer key
到此这篇关于c#
与java tcp
通道加密通信实例的文章就介绍到这了,更多相关c#
与java tcp
通道加密通信内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
6、参考博文
上一篇: C# 提取PDF中的表格详情