Non-symmetric encryption algorithm RSA usage precautions

Source: Internet
Author: User
Tags decrypt dotnet asymmetric encryption

Original: Asymmetric encryption algorithm RSA usage precautions

The first and most important one--rsa cannot encrypt more than 117 bytes of data! Remember! In fact, there is no need to ask for greater data encryption, although there are already relevant solutions, such as BigInteger project. But it's really important to note that if you encrypt data that is larger than 117 bytes, it's a bit confusing to say that it's thrown out. Consider the main use of RSA can be understood, generally we use RSA is the main purpose of digital signature, but also the "symmetric encryption" algorithm key and IV vector encryption;

Second, suppose you want to encrypt some data in a text file (such as an XML file), and then write a text file after it is encrypted? (If the encrypted byte array is written directly to the file as a stream, there is no problem) This involves a byte[] to string conversion problem, some people will say immediately, this is simple, With Encoding.Default.GetString Bai, if so, there will be no this problem! If you use Encoding.Default.GetString to save the encrypted results to a file and then decrypt it, you will encounter the following exception:

System.Security.Cryptography.CryptographicException message= "Incorrect data was not processed. /r/n "source=" mscorlib "StackTrace: In System.Security.Cryptography.CryptographicException.ThrowCryptogaphicExce Ption (Int32 hr) at System.security.cryptography.utils._decryptkey (Safekeyhandle Hpubkey, byte[] key, Int32 dwFlags) In System.Security.Cryptography.RSACryptoServiceProvider.Decrypt (byte[] RGB, Boolean FOAEP) in crse3363ae_lab0 1.program.decrypt () position d:/training/dotnet Framework 2.0/Sample program/CRSE3363AE_LAB01/CRSE3363AE_LAB01/CRSE3363AE_LAB01/ Program.cs: line number 286 in CRSE3363AE_LAB01. Program.main () position d:/training/dotnet Framework 2.0/Sample program/CRSE3363AE_LAB01/CRSE3363AE_LAB01/CRSE3363AE_LAB01/ Program.cs: Line number 56 in system.appdomain._nexecuteassembly (Assembly Assembly, string[] args) in SYSTEM.APPDOMAIN.E xecuteassembly (String assemblyfile, Evidence assemblysecurity, string[] args) in Microsoft.VisualStudio.HostingProce Ss. Hostproc.runusersassembly () in System.threadIng. Threadhelper.threadstart_context (Object State) in System.Threading.ExecutionContext.Run (ExecutionContext executionc Ontext, ContextCallback callback, Object State) in System.Threading.ThreadHelper.ThreadStart () InnerException:

The reason is because using Encoding.Default.GetString () to encrypt the byte[] (for the sake of convenience, given here a variable name right) for processing, then write to the text file, When decrypting, use Encoding.Default.GetBytes () to convert the encrypted content (string type) to byte[] array, this time the byte[] Array (variable name: wrong) is not the right variable in the previous article, The content and size are different! You take a wrong string to decrypt of course will report "incorrect data", it is not true!

Oh! Here's how to work around this problem (only the code that's relevant to the problem is provided below):

1) encryption

byte[] Value = RSA. Encrypt (Encoding.Default.GetBytes (temp), false); Using the public key to encrypt var stringBuilder = new StringBuilder (); Declares a variable that holds the byte[] converted character for (int i = 0; i < value. Length; i++) {stringbuilder.append (Value[i]. ToString ("X2")); The X2 is a 16 binary number converted to two bits, the converted length is twice times the length of the encryption: 256 bits} savetofile ("1.dat", stringbuilder.tostring ()); Write File

2) Decryption

byte[] tmp = GetBytes (ReadFromFile ("1.dat")); byte[] Value = RSA is provided after the//getbytes function. Decrypt (tmp, FALSE); Use the private key to decrypt normally, no more annoying data incorrect error Console.WriteLine (Encoding.Default.GetString (value));//Show decrypted data GetBytes function as follows: private Static byte[] GetBytes (string hexstr) {var rtnbytearray = new byte[hexstr.length/2];//establishes a byte array int j = 0; for (int i = 0; i < hexstr.length; i = i + 2) {string tmp = Hexstr.substring (i, 2);//two bits per read and then converted to decimal Rtnbytearray[j++] = Convert.tobyte (Convert.ToInt32 (TMP, 16));//Convert to byte type} return Rtnbytearray; }

Okay, now it's all ok!!. By the way, RSA cannot decrypt data that is more than byte.

PostScript, today suddenly thought can Base64 code, looks forward detour, below we use BASE64 code again to achieve once, very simple:

1) encryption

byte[] Value = RSA. Encrypt (Encoding.Default.GetBytes (kvp. Value), false); Enpatient.add (convert.tobase64string (value)) ;

2) Decryption

byte[] Value = RSA. Decrypt (Convert.frombase64string (kvp. Value), false);d Epatient.add (Encoding.Default.GetString (value));

Non-symmetric encryption algorithm RSA usage precautions

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.