Cryptography in. net

Source: Internet
Author: User
Tags mcrypt net cryptography asymmetric encryption
In. Before. net, it was very painful to use an unmanaged win32apis to encrypt and decrypt data. For this purpose of encryption and decryption ,. Net is configured with a group of classes (and namespaces ). Now you have many classes that can use different Algorithm Protect your data. In. In the. NET file, the crypttography namespace defines three types of encryption methods. They are asyuncricalgorithm, abstrricalgorithm, and hashalgorithm. All of these classes (and. Net cryptography type) are abstract classes. We are going to describe tricricalgorithm today. The rest will be later Article .

Note: although most managedCodeThe encryption class implementation in uses a lot of CryptoAPI libraries.

Symmetricalgorithms Basics

Symmetric algorithms work with users' keys (passwords. It means that you can implement it at any time and use symmetric algorithms to encrypt or decrypt your data. to encrypt or decrypt your data, you must define a password or a key. The following describes the features of symmetric encryption.

The encryption strength depends on your key (password ). If you configure a long key, it will be very difficult to crack. It takes a long time for a hacker to find the key.

One Risk of symmetric encryption is that the password should be known to the second person (this person must use your key to decrypt the data ).

This encryption algorithm is based on simple mathematical operations, so it works very fast. Therefore, it is the best choice when you want to encrypt a large amount of data.

Symmetric encryption can be cracked by hackers. However, if you define a very good password (long enough), the cracking process will take a long time.

Once the user defines the key. Hackers can use brute-force cracking or dictionaries to encode or decrypt your information. However, long keys can protect your data for a longer period of time when hackers crack your password.

In addition, it is very important to use symmetric encryption of keys or passwords. Is the initialization vector (IV ). IV is used in the initial encoding (encryption or decryption ). Among all symmetric algorithm classes, we have an attribute named mode. This is used by iv. If the mode attribute is set to ciphermode. CBC (Cipher Block Chaining), this mode is used. Each data block is processed using the value from the previous block. This means that if the system is processing the third data block, it will take some information from the second (processing the third data block ). Next, it uses the information in the first data block to process the second data block. However, there is no usable block before the first data block, so it uses IV to process the first block. This technology ensures that no two identical blocks generate the same output and therefore make the data safer. However, if you make mode = ciphermoder. ECB (Electronic codebook mode), he will not use the above method (use the block information previously processed to process the block following ). If you want to process a large number of messages with a small amount of resources and time, this method is very useful for you. It also allows you to process data from the middle.

At this point, we have included two very important things in symmetric encryption. They are key and Initialization vectors. Now let's look at the algorithms supported by symmetric encryption.

Symmetric algorithms and symmetric algorithms

Below are the key information of symmetric algorithms and their classes.

Algorithm name
Algorithm class (Abstract)
Valid key size (BIT)
Default key size (BIT)
Default implementation class

Des
Des
64
64
Descryptoserviceprovider

Tripledes
Tripledes
128,192
192
Tripledescryptoserviceprovider

RC2
RC2
40-128
128
Rc2cryptoserviceprovider

Rijndael
Rijndael
128,192,256
256
Rijndaelmanaged

Note that all algorithm classes inherit from the abstract class symmetricalgorithm. You can see that each class supports different key sizes. In the same case, they also support different sizes of Initialization vectors. As I mentioned earlier, all their classes are abstract classes, so we cannot directly create any instances of these abstract classes. However, the symmetricalgorithm class (also an abstract class) has a shared method called create. You don't have to worry about how it is implemented to create a specific instance of the class. It means that you can use it in the following ways.

RC2 mrc2 = rc2.create ();

It returns an instance implemented by RC2 by default, instead of worrying about how to implement RC2. This technology is very useful if you want to update the implementation of RC2 classes in the future at Microsoft and share code (possibly. In that case, your code will automatically adapt to their changes and work correctly. Or in the future, the RC2 class may be written with managed code, and your code can still accept it. In the same case, you can also use the following statement.

RC2 mcrypto = maid. Create ("RC2 ");

This also returns an RC2 object (implemented by default ). In this case, you need to use the duplicate create method to set parameters with the algorithm name to return the algorithm objects. The create method comes from the symmetricalgorithm class, and all other classes using symmetric algorithms mentioned above inherit from symmetricalgorithm. Therefore, you can find the create method in all the classes above. This means that if you use rc2.create ("des"), it will also work and return a des object. However, you cannot use the RC2 class to obtain the des object.

The above mechanism looks very useful. We can use our own algorithms to define our own classes in the same way. To do this, we must make some minor changes to the machine. config file. I will not describe it in detail here. You can refer to wrox's book on cryptography for more information.

Now let's take a look at some methods and attributes in the symmetricalgorithm class.

Blocksize: The size of data blocks processed separately. Big Data will be divided into small data blocks for processing. If the data size is smaller than the block size, it will be appended (fill with some default values ).

Key: the key will be used when processing data. This key is configured to use byte arrays.

IV: Use Initialization vectors for data processing (as described above ). Configure it as a byte array.

Keysize: The size of all bits of the key.

Legalblocksize: The returned blocksize enumeration tells you to determine the size of the block, including the maximum value, minimum value, and hop value. The Skip value indicates how many values should be added to the next value. For example, if the minimum value is 32 and the Skip value is 16, the next judgment value is 48 and 64. (Returns the blocksize enumeration which tells you legal values for block size including max value, Min value and skip value. skip value means that how much value shocould be added to last legal value to get next value. like if Min value is 32 and skipvalue is 16, it means next legal values will be 48, 64 and so on .)

Mode: Bit operation or set mode. See the description above. The value is one in the hermode enumeration.

Padding: obtains or sets an append value in the paddingmode enumeration. (Fill in the hollow area of the block)

Legalkeysize: Same as legalblocksize, but the key size is processed.

Create: as described above, use it to create instances of classes implemented by default algorithms.

Createencryptor: returns an icryptotransform object that can encrypt data manually. I will describe it carefully later.

Createdecryptor: returns an icryptotransform object that can decrypt data manually. I will describe it carefully later.

Generatrkey and generateiv: If key and IV are null during encryption or decryption, these methods can generate default keys and IV.

Vaildkeysize: Check whether the given key is a valid key of the algorithm.

Clear: clears and removes all resources and memory information such as keys and IV.

Before writing code, let's talk about a few things that are very helpful for us to understand the code.

Createencryptor and createdecryptor

The createencryptor and createdecryptor methods of the symmetricalgorithm class return the icryptotransform object. Icryptotransform is an interface implemented by the class to process data blocks. This process can be encrypted, decrypted, hashed, 64-based encoding and decoding, etc. The basic purpose of this interface is to complete data processing parts (the basic purpose of this interface is to perform blockwize processing of data .). You can directly use its instance, but in most cases, for convenience, we can do it through another name called cryptostream. Let's see how an example uses it.

Des mcrypt = new symmetricalgorithm. Create ("des ");

Icryptotransform mtransform = mcrypt. createencryptot ();

Createencryptor or createdecryptor are two methods for recutting. If you do not have any parameters, the default key and IV will be used (use the generatekey and generateiv methods in the symmetricalgoruthm class ). On the other hand, you can pass in an IV and key to the objects of createencryptor and createdecryptor. As a result, encryption and decryption will use our own defined IV and key.

Cryptostream class

The cryptostream class is usually used to encrypt or decrypt data while reading or writing data. It simply wraps the original stream class stream. it uses the buffered access taking all worries from you to manage buffer, block sizes, padding etc. you can use the following code to get its instance.

Des mcrypt = fig. Create ("des ");

Icryptotransform mtransform = mcrypt. createencryptor ();

Cryptostream mstream = new cryptostream (filestream, mtransform, cryptostrammode. Read)

Filestream is the stream (or memorystream) of the original file requesting to read data from the hard disk or memory ). Now, you can use the mstream object and streamreader/streamwriter object to read and write data. When you want to read and write data, your encrypted and decrypted information will depend on the icryptotransform object.

Code example

Now we have enough information about symmetricalgorithm. Finally, let's look at the code snippets to be encoded and decoded. Suppose you have a form that contains txtdata and command button controls. Write the following code in the Code event of the command button. This code will encrypt the text in textbox and display it with MessageBox, and write the encrypted result back to textbox.

Symmetricalgorithm mcryptprov;

Memorystream mmemstr;

// Encrypt the data in txtdata, and then display the encrypted result in MessageBox and write it back to textbox.

// You can configure anything here. Net supported classes

Des mcryptprov = fig. Create ("Rijndael ");

// Encrypted data will be stored in the memory as a stream. Therefore, we need the memory stream object.

Mmemstr = new memorystream ();

// Create an icrypttransform object. (Here we use the default key and initial vector ).

Icrypttramsform mtransform = mcryptprov. createencryptor ();

Cryptostream mcswriter = new cryptostream (mmemstr, mtransform, cryptostreammode. Write );

Streamwriter mswriter = streamwriter (mcswriter );

Mswriter.writer(this.txt data. Text );

Mswriter. Flush ();

Mcswriter. flushfinalblock ();

One thing to note here is that we didn't use IV and keys anywhere in the code. In fact, when we do not specify them in the code. Net Framework will be automatically generated for us. However, the example code in this article uses the user-specified key and IV. We use memorystream to write encrypted data to the memory. Now let's get the data code from the memory.

// The data has been written into the memory, but we need to echo it into textbox and MessageBox, so do the following.

// Create a byte array for the accepted data.

Byte [] Mbytes = new byte [mmemstr. Length-1];

Mmemstr. Position = 0;

Mmemstr. Read (Mbytes, 0, mmemstr. Length );

Text. utf8encoding menc = new text. utf8encoding ();

String mencdata = menc. getstring (Mbytes );

MessageBox. Show ("encrypted data: \ n" + mencdata );

This.txt data. Text = mencdata;

The conversion from byte to string must be encoded. Here I used utf8encoding. Finally, let's display the decrypted data in MessageBox and textbox again.

// Now let's get the decrypted data from the memory

// Because our data is in the memory, we need to re-use the memorystream object.

// Set the memory point to 0

Mmemstr. Position = 0;

Mtransform = mcryptprov. createdecryptor ();

Cryptostream mcsreader = new cryptostream (mmemstr, mtransform, cryptostreammode. Read );

Streamreader mstrreader = new streamreader (mcsreader );

String mdecdata = mstrreader. readtoend ();

MessageBox ("decrypted data: \ n" + mdecdata );

This.txt data. Text = mdecdata;

This is all the work. We use the same memory stream to decrypt the data. In order to read data from the actual part of the stream, we first set it to start. Then we use the createdecryptor method of the symmetricalgorithm object to create the icryptotransform object. In the above Code, we used an object (mmemstr) repeatedly for decryption ). You can create new objects (using new variables ). Then we need a streamreader object to read data from the memory. While reading that it will also decrypt that data since we passed cryptostream object during the creation of streamreader object.

Last words

. NET provides us with a very good way of hosting to protect our data. We can use it. Net built-in a group of classes to encrypt our data. Although many classes still use crypto APIs Technology in the background, there is no problem in using the old crypto APIs. However, we can safely use these classes without worrying about the specific implementation of those classes. In the following article, I will describe the myth and usage of asymmetric encryption algorithms.

Examples

The example code in this article allows you to select an algorithm to encrypt or decrypt data. It also allows you to specify your own IV and key. The code works in two ways. One is Textbox, which means you write something in textbox and then encrypt or decrypt the content. Second, you can select the file to be encrypted or decrypted.

Http://www.codeproject.com/dotnet/crypto_net.asp

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.