RSA key C # format and Java Format conversion

Source: Internet
Author: User
Tags modulus asymmetric encryption java format

Objective

Recently, due to project requirements, the service driven by C #, and the client was written by Java. The communication data uses RSA asymmetric encryption. However, the key format generated by Java and C # is not the same, so you need to convert the format to work properly. Search the Web to use Java Format Conversion code (such as: http://blog.csdn.net/road2010/article/details/40071881), this article will give a C # implementation method.

The key format Java key format is as follows:

Private:

miicdwibadanbgkqhkig9w0baqefaascamewggjdageaaogbakszssedphv77o5ocnlngxeq21qjdarc1+yid+9/ py5bxkzk5vcb49epfmwnuklv6ajqofthzpnos1t015fdeyiunkic2qvxrwa0xtefp6n8d4wqxrws4fng27jk5kp45s+ 9kljtx5hs7g97amczehiwphao6j9inomjlu8l62kzagmbaaecgyeamk3trtmwrjb33ognn9oefumyfy92qxi3x6hq1o6qdbw2qkd4bimfv+ Ni6ainyovuaadt2y+lq4dkgccvjzozvpm1vkxd2y7xka8/vebprirtt0qnpq9t7ujkpdsixf/zomfwdjc3ua1bpnq65rwhsj7zae+ gd7xnyce5meyijlecqqdvyqqwdqovlz5ljuuifuirhv26gvuotx8v60+opcz4/ mdfh6jleficvd6saayvufxbhvfy26jicnlr62zoibonakeaxxhsuennjnqcqhevtpzoulbmbtv1vzidq1zjg8fvu8sv6ibycr5+esc8n3/ 6rkw8/icjdzxe++vhzhosqsodvqjbam6/63j/rpndairj7vyjopljsc9/u3sh2gmjat7kc9uxvuldlsixtf3xuepplkbljeuxbfklnzm586a+ 6xqpvoucqdfotltolarbbmihyuee7qnhqhk63qbyj9rddp5qgo2mg4o7quxa6vsr4qzpsugqbx/ yidlfs8ulu3igv9zynekcqadayr8dctyzg0ebgdcorda5szc62pyrs2wk89wuxyl4fydl3omkvmkvtu5tccy7xht2ikjzrqefz3ds7asm8/4=

Public:

migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqckmukhht4b++zuahjyzrl3kntaiqwkwtfsihfvf6wow15gzobwgeprkxzmdbpc7+ gcaqh04wtztrnbdnex3rgcfj5chnkfcucgtmu3ht+jfa+fkf0vrohzrtuysuzd+obpvspsbceyboxve2jhm3osfqr2juo/ Ypzpo5vpjetimqidaqab
. NET key format is as follows:

Private:

<RSAKeyValue> <modulus>pjljir0+g/vs7mhycs0zd5dbwokmcslx7ih373+ljltermtm8ihj0sl8za26qu/ oamqh9ofk806zw3txl90rghseqhzzbxfhbrtfn4u/o3wphzbdfazh80bbskrmq/jmz70qum3hmgzsb3toxzn6ehakdo7qp2kc6aovtyxrypk= </Modulus> <Exponent>AQAB</Exponent> <p>1wkkfg6jls2ezsvlih1ck4b9uhr7qe1/l+tpqkqs+ Pzhx4eizxnyalq+kggml7n1wr1rwnuiyndzuetmtogadq==</p> <Q> Xxhsuennjnqcqhevtpzoulbmbtv1vzidq1zjg8fvu8sv6ibycr5+esc8n3/6rkw8/icjdzxe++vhzhosqsodvq==</q> &LT;DP&GT;ZR /rcn+umd0aisnu/ik48smxz39tdifaawkbpsol1re+6v2wylg1/fg4smmupsumrrdt+swdmbnzpr7peo++hq==</dp> <DQ> Mwi2w04sbeegakfi4qtuo2faetrdbvin2t0m/lccjyydijtc5drpvkvhbk+xqzaff9iimswzxqttcibx3pi0sq==</dq> < Inverseq>wgefa3lwm4nhgrnxdqwwous3otqwk0tsjppcfmci+bcgy96jpftcr7bubxhmu14bdopcwuann2d3uuwepvp+</inverseq > <d>mk3trtmwrjb33ognn9oefumyfy92qxi3x6hq1o6qdbw2qkd4bimfv+ni6ainyovuaadt2y+ Lq4dkgccvjzozvpm1vkxd2y7xka8/vebprirtt0qnpq9t7ujkpdsixf/zomfwdjc3ua1bpnq65rwhsj7zae+gd7xnyce5meyIjle=</d></rsakeyvalue> 

Public:

<RSAKeyValue>  <modulus>pjljir0+g/vs7mhycs0zd5dbwokmcslx7ih373+ljltermtm8ihj0sl8za26qu/ oamqh9ofk806zw3txl90rghseqhzzbxfhbrtfn4u/o3wphzbdfazh80bbskrmq/jmz70qum3hmgzsb3toxzn6ehakdo7qp2kc6aovtyxrypk= </Modulus>  <Exponent>AQAB</Exponent></RSAKeyValue>

  

Transform implementation Code (C #)

Format conversion to use an open source encryption library bouncy Castle Crypto APIs, website address: http://www.bouncycastle.org/csharp/

The specific implementation code is as follows:

Using system;using system.xml;using org.bouncycastle.asn1.pkcs;using org.bouncycastle.asn1.x509;using Org.bouncycastle.crypto.parameters;using org.bouncycastle.math;using org.bouncycastle.pkcs;using Org.bouncycastle.security;using org.bouncycastle.x509;///<summary>///RSA key format conversion///</summary>public Class rsakeyconvert{//<summary>//RSA private key format conversion, java->.net///</summary>//<param name= " Privatekey ">java generated RSA private key </param>///<returns></returns> public static string Rsaprivatekeyjava 2DotNet (String privatekey) {rsaprivatecrtkeyparameters Privatekeyparam = (rsaprivatecrtkeyparameters) PrivateKey        Factory.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&Gt;</rsakeyvalue> ", Convert.tobase64string (privateKeyParam.Modulus.ToByteArrayUnsigned ()), Con Vert. ToBase64String (privateKeyParam.PublicExponent.ToByteArrayUnsigned ()), Convert.tobase64string (PRIVATEKEYPARAM.P. Tobytearrayunsigned ()), convert.tobase64string (privatekeyparam.q.tobytearrayunsigned ()), Convert.ToB Ase64string (privateKeyParam.DP.ToByteArrayUnsigned ()), convert.tobase64string (PrivateKeyParam.DQ.ToByteArrayUns Igned ()), convert.tobase64string (privateKeyParam.QInv.ToByteArrayUnsigned ()), convert.tobase64string    (privateKeyParam.Exponent.ToByteArrayUnsigned ())); }///<summary>//RSA private key format conversion,. Net->java///</summary>/<param name= "Privatekey" >.net Generated private key </param>///<returns></returns> public static string Rsaprivatekeydotnet2java (String private        Key) {XmlDocument doc = new XmlDocument (); Doc.  LOADXML (Privatekey);      BigInteger m = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelementsbytagname ("modulus") [0].        InnerText)); BigInteger exp = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelementsbytagname ("Exponent") [0].        InnerText)); BigInteger d = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelementsbytagname ("D") [0].        InnerText)); BigInteger p = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelementsbytagname ("P") [0].        InnerText)); BigInteger q = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelementsbytagname ("Q") [0].        InnerText)); BigInteger DP = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelementsbytagname ("DP") [0].        InnerText)); BigInteger dq = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelementsbytagname ("DQ") [0].        InnerText)); BigInteger QINV = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelEmentsbytagname ("Inverseq") [0].        InnerText));        Rsaprivatecrtkeyparameters Privatekeyparam = new Rsaprivatecrtkeyparameters (M, exp, D, p, Q, DP, DQ, QINV);        Privatekeyinfo privatekeyinfo = Privatekeyinfofactory.createprivatekeyinfo (Privatekeyparam); byte[] serializedprivatebytes = Privatekeyinfo.toasn1object ().        Getencoded ();    Return convert.tobase64string (serializedprivatebytes); }///<summary>//RSA public key format conversion, java->.net///</summary>/<param name= "PublicKey" >java Health </param>///<returns></returns> public static string Rsapublickeyjava2dotnet (String PublicKey ) {Rsakeyparameters Publickeyparam = (rsakeyparameters) publickeyfactory.createkey (convert.frombase64string (publ        Ickey)); return string. Format ("<rsakeyvalue><modulus>{0}</modulus><exponent>{1}</exponent></ Rsakeyvalue> ", Convert.tobase64string (publicKeyParam.Modulus.ToByteArrayUnsigned ()), convert.tobase64string (publicKeyParam.Exponent.ToByteArrayUnsigned ())); }///<summary>//RSA public key format conversion,. Net->java///</summary>/<param name= "PublicKey" >.net </param>///<returns></returns> public static string Rsapublickeydotnet2java (String PublicKey        {XmlDocument doc = new XmlDocument (); Doc.        LOADXML (PublicKey); BigInteger m = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelementsbytagname ("modulus") [0].        InnerText)); BigInteger p = new BigInteger (1, convert.frombase64string (Doc. Documentelement.getelementsbytagname ("Exponent") [0].        InnerText));        Rsakeyparameters pub = new Rsakeyparameters (false, M, p);        Subjectpublickeyinfo publickeyinfo = Subjectpublickeyinfofactory.createsubjectpublickeyinfo (pub); byte[] serializedpublicbytes = Publickeyinfo.toasn1object ().        Getderencoded ();   Return convert.tobase64string (serializedpublicbytes); }} 

  

RSA key C # format and Java Format conversion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.