Encryption and decryption practice using the digital certificate of the number of certificates (iii)--Encrypt Long data with RSA certificate and symmetric encryption technology

Source: Internet
Author: User
Tags dotnet asymmetric encryption

This article all source code download:/files/chnking/encryptlongdata.rar

I. Use of certificates combined with symmetric encryption algorithm to add and decrypt Long data

The previous section discussed how to encrypt data using RSA certificates, which mentions: "The RSA implementation of dotnet has a characteristic that it must add some random numbers in the clear text, so the plaintext cannot fill 128 bytes, the actual test, the plaintext is up to 117 bytes, the space left to fill the random number". That is, for the 1024-bit key RSA, only 128 bytes of data can be encrypted at a time, for the RSA implementation of dotnet can only encrypt 117 bytes of data.

This raises the question of how to encrypt data over 128 bytes (or more than 117 bytes).

There is a way to divide the data into the appropriate size of the data block after block-wise encryption, decryption block-by-piece decryption and splicing. In fact, des (including tripledes) algorithm adopted this approach, the DES algorithm each time the data is split into 8 bytes of data block, one time to encrypt a block of data, the next block of data using the key and the previous data block encryption results are then encrypted, so block by bit encryption, Decryption is also the same, block-by-piece decryption and then stitching into plaintext. Dotnet provides the DES algorithm implementation of the DESCryptoServiceProvider (or TripleDESCryptoServiceProvider) class to these splitting, encryption, decryption, splicing process is implemented internally, Developers can assume that des can encrypt long data directly once without the developer having to deal with it.

Since des can do so, why the RSA algorithm does not do so, directly in the implementation of the RSA algorithm RSACryptoServiceProvider class automatically split the encryption and decryption splicing Long data?

Let's take a look at the respective characteristics of the symmetric algorithm (represented by DES) and the asymmetric algorithm (represented by RSA).

L Symmetric algorithm:

The encryption and decryption parties use the same key, there must be a key transfer process, the confidentiality of the key is a great risk.

The algorithm is relatively simple and the encryption and decryption speed is very fast.

L Asymmetric algorithm:

The encrypting party uses the public key in the key pair, and the decryption party uses the private key in the key pair.

The algorithm is complex and the encryption and decryption speed is slow. The RSA algorithm does not do this because the complexity of the RSA algorithm results in a slow encryption decryption, and does not advocate the use of RSA encryption of Long data, so dotnet's RSA implementation did not do so. Of course, developers can write their own code to split the encryption and decryption process, the implementation of RSA encryption of Long data functions. But this is not a good way, the more realistic way is: Asymmetric encryption technology and symmetric encryption technology to encrypt long data.

The concrete idea is this:

The cryptographic party generates a symmetric cryptographic key key (including key and IV), which is then used by the symmetric algorithm to encrypt the long data, and then the symmetric key key that was just generated is encrypted with the public key of the asymmetric algorithm provided by the decryption party, PublicKey. Finally, the encrypted long data and encrypted symmetric key keys are stitched together and sent to the decryption party.

After the decryption party is received, the data is decomposed first, and the encrypted symmetric key key and the encrypted long data are decomposed into two parts. Then the private key of the asymmetric algorithm is decrypted to obtain the symmetric key key. Finally, the encrypted long data is decrypted with the symmetric key key.

The following is an example of the RSA certificate generated in the previous section, combined with the TripleDES algorithm, which describes the implementation of asymmetric encryption technology and symmetric encryption technology to encrypt long data.

Figure 13. Encrypting and decrypting process with RSA combined with TripleDES algorithm

1. Generate certificates, distribute RSA certificates

The RSA certificate that is requested by the decryption party for the MakeCert, or the Mytestcert that is generated by the section "Using the" tools to obtain the. The decryption party will export its RSA certificate to a CER-type certificate with only the public key distributed to all cryptographic parties that may need to send encrypted messages to themselves.

The System.Security.Cryptography. TripleDESCryptoServiceProvider class is the main class that implements the TripleDES algorithm in dotnet.

2. Encrypt party generation TripleDES algorithm key and IV

The TripleDESCryptoServiceProvider class has only one constructor method, TripleDESCryptoServiceProvider (), which initializes some properties:

KeySize (encryption key length, in bits) = 192 (24 bytes)

BlockSize (encrypted data block size, in bits) = 64 (8 bytes)

Feedbacksize (the size of data returned after encrypting a block, in bits) = 64 (8 bytes)

The TripleDESCryptoServiceProvider construction method initializes a set of random keys and IV.

The default TripleDESCryptoServiceProvider key is 24 bytes (16 bytes of key can also be generated), the IV is 8 bytes, and the encrypted data block is 8 bytes.

The code for generating key and IV is simple:

TripleDESCryptoServiceProvider tdesalg = new TripleDESCryptoServiceProvider ();

byte[] Keyarray = Tdesalg.key;

byte[] Ivarray = TDESALG.IV;

3, using RSA public key encryption TripleDES algorithm key and IV3.1. Get RSA Public key

The cryptographic party obtains the CER certificate with the public key provided by the decryption party and obtains the RSA public key by reading the CER certificate file (you can, of course, load the certificate into the certificate store and then read the certificate to the certificate store to get the public key).

To load a certificate from a certificate file that contains only the public key

X509Certificate2 myx509certificate2 = new X509Certificate2 (@ "... /.. /.. /mytestcert.cer ");

Obtain a RSACryptoServiceProvider with a public key from the certificate

RSACryptoServiceProvider Publickeyprovider = (RSACryptoServiceProvider) MyX509Certificate2.PublicKey.Key;

3.2. RSA encryption Key and IV

Both the key and IV are in the form of byte[], to connect them two after the encryption, it is necessary to consider how to decrypt after the two can be accurately split open.

Byte[] is a byte array, key and IV and TripleDESCryptoServiceProvider class randomly generated, each byte can be any value, if the key and IV directly connected to the byte[], after the encryption decryption, split them, The contents of the key and IV itself cannot be segmented, and there is no distinction between the two parts of the content. Of course, the length of the key and IV itself can be split, but the length of the key is not fully determined, the DES algorithm key is 8 bits, the TripleDES algorithm key is 16-bit or 24-bit, so it is not a good way to split by length.

The general practice is to add a delimiter directly to the key and IV, the two parts of the data are concatenated by the delimiter, and later split the separator by separating the different parts of the delimiter on the line.

Again, since both sides of the content is randomly generated, it may be any value, how to ensure that the contents of the two sides are not the same as the delimiter, if it happens that the contents of the two sides with the same delimiter part of the trouble, the split out of the data must be wrong.

You can make a transformation of the content that needs to be connected, convert it to another encoding, and the delimiter takes the impossible characters in the encoding.

The general choice is Base64 encoding, which contains only 64 characters, that is: uppercase A-Z, lowercase A-Z, number 0-9, ' + ' and '/'. For further information on Base64 coding, please refer to: http://www.cnblogs.com/chnking/archive/2007/08/12/852669.html

Encode the key and IV separately, and then set a delimiter (such as "ßà", such as the impossible characters in the Base64), and base64 them before encrypting them.

Key and IV using RSA public key Cryptography TripleDES algorithm

String keyandiv = convert.tobase64string (keyarray) + separator +convert.tobase64string (ivarray);

Key and IV of TripleDES algorithm with RSA public key encryption

byte[] keyandivbytesencrypted = publickeyprovider.encrypt (encoding. GetBytes (Keyandiv), false);

The encrypted key and IV are then converted to base64 strings.

String keyandivstrencrypted = Convert.tobase64string (keyandivbytesencrypted);

4. Encrypt long data with symmetric key

Set up a MemoryStream, which stores the encrypted data stream

MemoryStream mstream = new MemoryStream ();

Create a new CryptoStream object using MemoryStream and key, IV

CryptoStream cstream = new CryptoStream (Mstream,

New TripleDESCryptoServiceProvider (). CreateEncryptor (Keyarray, Ivarray),

CryptoStreamMode.Write);

Convert the plaintext string to the byte[of the specified code page]

byte[] Plaintextarray = encoding. GetBytes (plaintext);

Writes the encrypted byte stream to the MemoryStream

Cstream.write (Plaintextarray, 0, plaintextarray.length);

Update the last state in the buffer to MemoryStream and clear the Cstream buffers

Cstream.flushfinalblock ();

Stream encrypted data into a Base64 string

String longdatastrencrypted = Convert.tobase64string (Mstream.toarray ());

Close two streams.

Cstream.close ();

Mstream.close ();

Data to be encrypted may have two forms, one is binary data, itself is a set of byte stream, such data can skip this step, directly into the encryption step. Another case is string data, where the same characters in a string use different code pages to generate different bytecode, so a conversion from string to byte stream is required to specify what encoding to use. After decryption, the conversion from a byte stream to a string will be decoded using the same code page, or garbled.

In fact, when a byte[] type is directly converted to a string type, you need to specify the code page, because each code page encodes the same character differently, meaning that the same character corresponds to a different binary code in a different codepage.

In this example, there is a large number of byte[] types in the encryption and decryption process of the conversion between the string type, so in the example used to pre-defined a encoding type of object Encoding,utf-8 code page, in this case all involved byte[] The conversion between a type and a string type takes the same encoding, and is guaranteed to be converted using the same code page.

5, after the connection encryption of the symmetric key connection after the encryption of Long data

As in the case of keys and IV, the encrypted symmetric key and the encrypted long data also need to be connected, as is the same delimiter.

Connect the encrypted long data with a delimiter with the encrypted des key as a string

String resultencryptedstr = longdatastrencrypted + separator + keyandivstrencrypted;

Encrypted data with encrypted key, IV connected Base64 string is then converted to byte[] for delivery

Byte[]resultencryptedbytes = Encoding. GetBytes (RESULTENCRYPTEDSTR);

The encryption process data has a form change:

Figure 14. RSA combined with DES encryption to decrypt large data data in the form of changes?--encryption process

Above is the encryption process, the following is the decryption process.

6. Split the encrypted symmetric key after the encrypted long data

The decryption process needs to be used several times to split the string function, write a method of splitting the string:

<summary>

Separates the strings on both sides of the delimiter according to the delimiter

</summary>

<param name= "Value" > Delimited string </param>

<param name= "Separator" > Separators </param>

<returns></returns>

private static string[] Splitbystring (string value, string separator)

{

int separatorpos = value. IndexOf (separator);

string[] returnvalue = new string[2];

Returnvalue[0] = value. Substring (0, Separatorpos);

RETURNVALUE[1] = value. Substring (Separatorpos + separator. Length);

Return returnvalue;

}

The decryption party uses the method above to split the received data into two parts, encrypted long data and encrypted symmetric keys.

Splitting encrypted long data and encrypted symmetric keys

string[] Encrypteddataarray = splitbystring (encoding. GetString (cryptographic), separator);

Encrypted Long data

String longdatastrencrypted = Encrypteddataarray[0];

Encrypted symmetric key

String keyandivstrencrypted = Encrypteddataarray[1];

7, decryption TripleDES algorithm key and IV7.1. Get RSA Public key

The decryption party obtains the RSA private key from its own PFX certificate file (you can, of course, load the certificate into the certificate store and then read the certificate to the certificate store to get the private key). When loading a certificate that contains a private key, you need to provide a private key protection password.

To load a certificate from a certificate file, if you have a private key, you need to provide the password you set when saving the certificate

X509Certificate2 myx509certificate2 = new X509Certificate2 (@ "... /.. /.. /mytestcert.pfx "," password ");

Obtaining a RSACryptoServiceProvider with a private key from the certificate

RSACryptoServiceProvider Privatekeyprovider = (RSACryptoServiceProvider) Myx509certificate2.privatekey;

7.2. RSA decryption Key and IV

Encrypted symmetric key Base64 string converted to byte[]

byte[] keyandivbytesencrypted = convert.frombase64string (keyandivstrencrypted);

Decrypts the encrypted symmetric key and turns it into a string

String keyandiv = Encoding. GetString ((Publickeyprovider.decrypt (keyandivbytesencrypted, false)));

Split Key and IV

string[] Keyivarray = splitbystring (keyandiv, separator);

The original form of restoring key from Base64 string to byte[]

byte[] Keyarray = convert.frombase64string (keyivarray[0]);

The original form of restoring IV from Base64 string to byte[]

byte[] Ivarray = convert.frombase64string (keyivarray[1]);

8. Encrypt Long data encrypted with symmetric key

byte[] longdatabytesencrypted = convert.frombase64string (longdatastrencrypted);

Set up a MemoryStream, which stores the encrypted data stream

MemoryStream msdecrypt = new MemoryStream (longdatabytesencrypted);

Create a new CryptoStream object using MemoryStream and key, IV

CryptoStream csdecrypt = new CryptoStream (Msdecrypt,

New TripleDESCryptoServiceProvider (). CreateDecryptor (Keyarray, Ivarray),

CryptoStreamMode.Read);

Based on the length of the ciphertext byte[] (may be longer than the plaintext before encryption), create a new byte[that holds the plaintext after decryption]

byte[] Decryptdataarray = new Byte[longdatabytesencrypted.length];

Read the decrypted data into the Decryptdataarray.

Csdecrypt.read (Decryptdataarray, 0, decryptdataarray.length);

Msdecrypt.close ();

Csdecrypt.close ();

9. Get clear Text Long data

Decrypted Long data byte[] turn into a string

String resultsrt = Encoding. GetString (Decryptdataarray);

The "/0" character after removing the string

int offset = Resultsrt.indexof ("/0");

String longdata = resultsrt.substring (0, offset);

Finally get the long data in clear text, one thing to be aware of.

Des Encryption is a block of 8 bytes, if the length of the plaintext is not an integer multiple of 8 bytes, des will add a byte with a value of 0 after the clear text to fill 8 bytes of data block, and then encrypt. After such data is decrypted, the added "/0" still exists and needs to be removed.

The decryption process data has a form change:

Figure 15. RSA combined with DES encryption to decrypt large data data?--decryption process

Reference

. NET in the management of digital certificates (Certificate) Some classes

Create a X509 certificate and get a little research on the certificate key

Encryption and decryption practice using the digital certificate of the number of certificates (iii)--Encrypt Long data with RSA certificate and symmetric encryption technology

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.