RSA encryption and decryption interaction between C # Java

Source: Internet
Author: User
Tags base64 decrypt modulus

Reference: http://blog.csdn.net/dslinmy/article/details/37362661

Here, the RSA algorithm plus decryption between C # and Java interaction between the problem, these two days tangled for a long time, but also read a lot of other people write articles, quite benefited, but did not solve my actual problems, finally, or I have been tinkering out.

First of all, introduce the purpose of writing this code: to complete the WebService verification problem, the server-side use C # development, the client in Java development. The server side provides the public key to the client, the data is encrypted, the client encrypts and submits the data to the server, and the server decrypts the data with the private key to verify.

The main problem here is that the public and private keys generated by the C # RSACryptoServiceProvider class are XML string data, and the Java RSA algorithm requires modulus, exponent are biginteger types, The transition between the two is the problem.

About Java and C # separate RSA encryption and decryption, you can see the entire two articles, Java RSA Encryption and decryption implementation () and C # RSA encryption decryption and signature and authentication implementation.

Now let's talk about the implementation steps:

First, the C # RSACryptoServiceProvider class generates a public key, a private key

/// <summary>         ///generate public key, private key/// </summary>         /// <returns>public key, private key, public key "publicly", private key "private"</returns>          Publicdictionary<string,string>Createkeypair () {Dictionary<string,string> KeyPair =Newdictionary<string,string>(); RSACryptoServiceProvider provider=NewRSACryptoServiceProvider (1024x768); Keypair.add (" Public", provider. Toxmlstring (false)); Keypair.add ("PRIVATE", provider. Toxmlstring (true)); returnKeyPair; }  

The generated public key is

 <  rsakeyvalue       >  <  modulus  >  t+56m5jxxonajakc7mgkhazx5gwjtzojbslolplbgewiebfam+auukalfrx83/      hauv79zir3zuljolbdalx1cmcpk/b9fdnbllmzqi4cfsnfmmlwh05xf+zs1pkhskqtui3dfuu+3xh6ak+s38dpizuj/hihqqukysn6gj9h+c8=  </ modulus       >  <  exponent  >  Aqab</ exponent   >  </ rsakeyvalue  >  

Extracting modulus and exponent from the public key provided by C # on the client (Java)

/*** Returns HASPMAP containing modulo modulus and exponential exponent *@return      * @throwsmalformedurlexception *@throwsdocumentexception*/       Public StaticHashmap<string,string> RSAParameters (String xmlpublickey)throwsmalformedurlexception, documentexception{HashMap<string,string> map =NewHashmap<string, string>(); Document Doc=Documenthelper.parsetext (Xmlpublickey); String Mudulus= (String) doc.getrootelement (). Element ("modulus"). GetData (); String exponent= (String) doc.getrootelement (). Element ("Exponent"). GetData (); Map.put ("Mudulus", Mudulus); Map.put ("Exponent", exponent); returnmap; }  

Generate Public key Rsapublickey (Java) with modulus and exponent

Here is a key step to decode Mudolus and exponent first, which is due to the key pair generated by C #, whose parameters have been Base64 encoded as string, and the java RSA parameter is a Base64 type without byte[encoding.

As for the BASE64 encoding, decoding method, refer to this article, Java encoding and decoding, want to detail.

 Public Static byte[] decodeBase64 (String input)throwsexception{Class clazz=class.forname ("Com.sun.org.apache.xerces.internal.impl.dv.util.Base64"); Method Mainmethod= Clazz.getmethod ("Decode", String.class); Mainmethod.setaccessible (true); Object Retobj=mainmethod.invoke (NULL, input); return(byte[]) retobj; }            /*** Return RSA public key *@paramModules *@paramexponent *@return      */       Public Staticpublickey Getpublickey (string modulus, string exponent) {Try {               byte[] m =decodeBase64 (modulus); byte[] e =decodeBase64 (exponent); BigInteger B1=NewBigInteger (1, M); BigInteger B2=NewBigInteger (1, E); Keyfactory keyfactory= Keyfactory.getinstance ("RSA"); Rsapublickeyspec KeySpec=NewRsapublickeyspec (B1, B2); return(Rsapublickey) keyfactory.generatepublic (KEYSPEC); } Catch(Exception e) {e.printstacktrace (); return NULL; }         }  

After obtaining the public key, RSA encryption can be processed, there is a point to note that RSA encryption and decryption have a maximum length limit, the maximum length of encryption is 117 bytes, the maximum decryption length is 128 bytes, in addition, the data encrypted here is BASE64 encoding processing

 Public StaticString Encrypt (byte[] source, PublicKey PublicKey)throwsException {String encryptData=""; Try{Cipher Cipher= Cipher.getinstance ("RSA");              Cipher.init (Cipher.encrypt_mode, PublicKey); intLength =source.length; intOffset = 0; byte[] Cache; Bytearrayoutputstream OutStream=NewBytearrayoutputstream (); inti = 0;  while(Length-offset > 0){                  if(Length-offset >maxencryptsize) {Cache=cipher.dofinal (source, offset, maxencryptsize); }Else{Cache= cipher.dofinal (source, offset, length-offset); } outstream.write (Cache,0, cache.length); I++; Offset= i *maxencryptsize; }              returnencodeBase64 (Outstream.tobytearray ()); } Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(nosuchpaddingexception e) {e.printstacktrace (); } Catch(InvalidKeyException e) {e.printstacktrace (); } Catch(illegalblocksizeexception e) {e.printstacktrace (); } Catch(badpaddingexception e) {e.printstacktrace (); }          returnEncryptData; }  

The encrypted data is submitted to the C # Server for decryption, and of course, the maximum length limit is also a concern.

/// <summary>          ///RSA Decryption/// </summary>          /// <param name= "EncryptData" >ciphertext encoded by Base64</param>          /// <param name= "Privatekey" >private Key</param>          /// <returns>data after RSA decryption</returns>           Public Static stringDecryptstringEncryptData,stringPrivatekey) {              stringDecryptdata =""; Try{RSACryptoServiceProvider provider=NewRSACryptoServiceProvider (); Provider.                  Fromxmlstring (Privatekey); byte[] Bencrypt =convert.frombase64string (EncryptData); intLength =bencrypt.length; intoffset =0; stringCache; inti =0;  while(Length-offset >0)                  {                      if(Length-offset >maxdecryptsize) {Cache= Encoding.UTF8.GetString (provider. Decrypt (Getsplit (bencrypt, offset, maxdecryptsize),false)); }                      Else{Cache= Encoding.UTF8.GetString (provider. Decrypt (Getsplit (bencrypt, offset, length-offset),false)); } decryptdata+=Cache; I++; Offset= i*maxdecryptsize; }              }              Catch(Exception e) {Throwe; }              returnDecryptdata; }            /// <summary>          ///intercept byte array partial bytes/// </summary>          /// <param name= "input" ></param>          /// <param name= "offset" >start offset bit</param>          /// <param name= "Length" >Intercept Length</param>          /// <returns></returns>          Private Static byte[] Getsplit (byte[] Input,intOffsetintlength) {               byte[] Output =New byte[length];  for(inti = offset; I < offset + length; i++) {Output[i-offset] =Input[i]; }              returnoutput; }  

In this way, it has been completed successfully.

After testing, it did get the right result.

If there is any problem, I hope you correct me!

RSA encryption and decryption interaction between C # Java

Related Article

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.