RSA encryption solution that exceeds the 117-byte data error

Source: Internet
Author: User
Tags decrypt implement modulus
Encrypt | solve | data

A while ago to the Public Security Bureau to do the project, the use of public key encryption technology and symmetric key encryption technology. Information is encrypted through 3DES, and the key is routed through the RSA public key System. The client uses CPU card Ekey for decryption. However, in the process of system writing, it is found that the RSA encryption algorithm in. NET is to add some random numbers before the data is encrypted in order to improve security, so use. NET RSA encryption algorithm at a maximum of 117 bytes of data encryption (more than 117 bytes need to split into multiple pieces of encryption and then connected), after encryption to obtain a length of 128 bytes of encrypted data. But it can be a lot of trouble for a public key system that needs to be acknowledged by both parties. In my system, I need to implement the online encryption of the user's session key through the following steps:

Encryption process:
1, the session key to add random number, supplemented to 128 bits,
2, using the CA private key to decrypt, the result is 128-bit data,
3, the data using the user's public key encryption, get 128-bit data, transmission through the network.


Decryption process:
1, using the user's private key to decrypt the 128-bit data transmitted online;
2, the result using the CA public key encryption;
3, remove the random number used to confuse, extract the session key

However, RSA encryption in. NET can only operate on up to 117 bytes of data, causing 128-bit data to be processed in two parts, and the encrypted data is constantly expanding. In order to solve this problem and make the RSA encryption and decryption process consistent with the process on the Ekey, I had to write my own RSA encryption algorithm.

After looking at a lot of data, I decided to take advantage of ready-made BigInteger classes. You can refer to http://www.codeproject.com/csharp/biginteger.asp for more information. Using BigInteger, I added two methods Rsaencrypt and Rsadecrypt to implement RSA encryption decryption. This will no longer be subject to a 117-byte limit.

The following two sections of the program, the program is used. NET with RSA encryption algorithm to achieve encryption and decryption, but TextLength property once more than 117, the system will not be encrypted; Program two is a modified system, can be 128-bit data encryption, without a 117 limit. Program II omits the BigInteger class, if necessary from the http://www.codeproject.com/csharp/ biginteger.asp download, do not forget to annotate the main method, otherwise there will be a compilation error at compile time, saying there are two entry points (of course, you can also specify an entry point in the project properties).

Program One:

Using System;
Using System.Security.Cryptography;
Using System.Text;

Class Oldrsa
... {
static void Main ()
... {
int textlength = 117;
Byte[] EncryptedData;
Byte[] Decrypteddata;
      string Key1 = "<rsakeyvalue><modulus>4n6ejsx4qnfpp6h+ wcpdjz8ssmmrjevjabqegsoobhknepo/v3m94nf89+zl5llh7/lurgcufnizvieth/z9+h/ ydum0f3fjimn3utk1tk0ioff0cvc9lnerbeoejmkeqivujuc4c+bmqttn6urhfcy3r3zgp3feegqorljekvc=</modulus>< Exponent>aqab</exponent><p>7w2qsvrbn168ehc4v/fipml+7wukorrij9i8i21fs5glvyrja2czbzplkrahumloclgd /qkj0iapf17471nfkw==</p><q>8oztalinrk1vduvlhnppcnqsehbp9if5p+kwru07sfgwahnyewurg0epebvbgoe/1kzpkqb /wu8vsn4oeauohq==</q><dp>dih+5ouww5av7zlifvqdtents8b9uzbhcbvxry2vddaxbdr+swbse/gvmrg/ 9fmwk6zbhbopnj8tchkmqozhuq==</dp><dq>6g96q/gxeug3qk+dbp8hil9vsex5wd8ueigicv9/as/ 7iwqljgbama1xi8txrbo6mdbil2pgkf4uqeg5qeqzrq==</dq><inverseq>nyx28u1freiigxgx2s5+ pxbb8wq0xvxne2g2mt0vq9xqdhbaxefpfznjnaga8ahvlunahqg5urgry3ogqono4g==</inverseq><d>pvkj1r1ntc3lhu+ xgitvq9qe0tr9v6rcy7sfov9xbcm/ypf20q8sod3y0ad87u9ccssdwfjyagukai0wugjfgfalf8/4pfwqzrgblsn96klmklmy7c6oihlriw+ Myxmvaggsp3/r4se6wgk5ischjkikyv/pywoobdre6ordzie=</d></rsakeyvalue> ";

Try
... {
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider ();
Rsa. Fromxmlstring (Key1);

byte[] Datatoencrypt = generatebytes (textlength);
Console.WriteLine ("Original buff:" + convert.tobase64string (datatoencrypt) + "");

EncryptedData = RSA. Encrypt (Datatoencrypt, false);
Console.WriteLine ("Encrypted buff:" + convert.tobase64string (EncryptedData) + "");

Decrypteddata = RSA. Decrypt (Encrypteddata,false);
Console.WriteLine ("Decrypted buff:" + convert.tobase64string (decrypteddata) + "");
}
Catch
... {
Console.WriteLine ("Encryption failed.");
}
}

//***********************************************************************
Randomly generating a byte array of a specified length
//***********************************************************************
public static byte[] Generatebytes (int bytelength)
... {
byte[] buff = new Byte[bytelength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ();

The array is populated with password-enhanced random bytes
Rng. GetBytes (Buff);
return buff;
}
}

Program Two:

Using System;
Using System.Security.Cryptography;
Using System.Text;

Class Newrsa
... {
public static void Main ()
... {
int textlength = 128;
Byte[] EncryptedData;
Byte[] Decrypteddata;
      string Key1 = "<rsakeyvalue><modulus>4n6ejsx4qnfpp6h+ wcpdjz8ssmmrjevjabqegsoobhknepo/v3m94nf89+zl5llh7/lurgcufnizvieth/z9+h/ ydum0f3fjimn3utk1tk0ioff0cvc9lnerbeoejmkeqivujuc4c+bmqttn6urhfcy3r3zgp3feegqorljekvc=</modulus>< Exponent>aqab</exponent><p>7w2qsvrbn168ehc4v/fipml+7wukorrij9i8i21fs5glvyrja2czbzplkrahumloclgd /qkj0iapf17471nfkw==</p><q>8oztalinrk1vduvlhnppcnqsehbp9if5p+kwru07sfgwahnyewurg0epebvbgoe/1kzpkqb /wu8vsn4oeauohq==</q><dp>dih+5ouww5av7zlifvqdtents8b9uzbhcbvxry2vddaxbdr+swbse/gvmrg/ 9fmwk6zbhbopnj8tchkmqozhuq==</dp><dq>6g96q/gxeug3qk+dbp8hil9vsex5wd8ueigicv9/as/ 7iwqljgbama1xi8txrbo6mdbil2pgkf4uqeg5qeqzrq==</dq><inverseq>nyx28u1freiigxgx2s5+ pxbb8wq0xvxne2g2mt0vq9xqdhbaxefpfznjnaga8ahvlunahqg5urgry3ogqono4g==</inverseq><d>pvkj1r1ntc3lhu+ xgitvq9qe0tr9v6rcy7sfov9xbcm/ypf20q8sod3y0ad87u9ccssdwfjyagukai0wugjfgfalf8/4pfwqzrgblsn96klmklmy7c6oihlriw+ Myxmvaggsp3/r4se6wgk5ischjkikyv/pywoobdre6ordzie=</d></rsakeyvalue> ";

Try
... {
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider ();
Rsa. Fromxmlstring (Key1);
RSAParameters rsakeyinfo = RSA. Exportparameters (TRUE);

byte[] Datatoencrypt = generatebytes (textlength);
Console.WriteLine ("Original buff:" + convert.tobase64string (datatoencrypt) + "");

EncryptedData = Rsaencrypt (Datatoencrypt, rsakeyinfo.exponent, Rsakeyinfo.modulus);
Console.WriteLine ("Encrypted buff:" + convert.tobase64string (EncryptedData) + "");

         decrypteddata = Rsadecrypt (EncryptedData, RSAKEYINFO.D, Rsakeyinfo.modulus);
         Console.WriteLine ("Decrypted buff: " + Convert.tobase64string (Decrypteddata) + "");
     }
      catch
      ... {
         Console.WriteLine ("Encryption failed.");
     }
  }

//***********************************************************************
RSA Encrypt
//***********************************************************************
static public byte[] Rsaencrypt (byte[] datatoencrypt, byte[] Exponent, byte[)
... {
BigInteger original = new BigInteger (datatoencrypt);
BigInteger e = new BigInteger (Exponent);
BigInteger n = new BigInteger (modulus);

BigInteger encrypted = Original.modpow (e,n);
return Hexstringtobyte (encrypted. Tohexstring ());
}

//***********************************************************************
RSA Decrypt
//***********************************************************************
static public byte[] Rsadecrypt (byte[] EncryptedData, byte[] D, byte[] modulus)
... {
BigInteger encrypted = new BigInteger (EncryptedData);
BigInteger d = new BigInteger (d);
BigInteger n = new BigInteger (modulus);

BigInteger decrypted = Encrypted.modpow (d,n);
Return Hexstringtobyte (decrypted. Tohexstring ());
}

//***********************************************************************
Convert hexstring to byte[] Array
//***********************************************************************
static public byte[] Hexstringtobyte (string hexstring)
... {
byte[] Byteresult = new BYTE[HEXSTRING.LENGTH/2];

for (int i = 0; i < HEXSTRING.LENGTH/2; i++)
Byteresult[i] = Convert.tobyte (hexstring.substring (i*2,2), 16);

return byteresult;
}

//***********************************************************************
Randomly generating a byte array of a specified length
//***********************************************************************
public static byte[] Generatebytes (int bytelength)
... {
byte[] buff = new Byte[bytelength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ();

The array is populated with password-enhanced random bytes
Rng. GetBytes (Buff);
return buff;
}
}



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.