Key (cryptography) in net-symmetric encryption

Source: Internet
Author: User
Describes the use of unmanaged Win32apis encryption to decrypt data before. NET is a very painful thing to do. For the purpose of this cryptographic decryption. NET is configured with a set of classes (and namespaces). Now you have a lot of classes that can protect your data using each of these different algorithms. There are 3 types of encryption methods defined within the. NET Crypttography namespaces. They are asymmetricalgorithm,symmetricalgorithm and HashAlgorithm. All of these classes (and. NET cryptography type) are abstract classes. We are going to describe symmetricalgorithm today. The rest will be explained in later articles. Note: Although the cryptographic class implementations in most managed code use a lot of CryptoAPI libraries. Symmetricalgorithms the underlying symmetric algorithm works with the user's key (password). It means that anytime you can implement it and you can use the symmetric algorithm to encrypt or decrypt your data, you must define a password or a key to encrypt or decrypt your data. The following describes the characteristics of symmetric encryption. The strength of the encryption depends on your key (password). If you configure a long key, it will be very difficult to crack. It means that he will take a long time to get the hacker to find the key. One of the risks 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. So when you want to encrypt the amount of data is very large, it is the best choice. Based on symmetric encryption can be hacked brute force. But if you define a very good password (long enough), the cracking process will take a long time. Once the user has defined the key. Hackers can use brute force cracking or dictionaries to encode or decrypt your information. But long keys can protect your data for longer periods of time when hackers crack your password. In addition, there is a very important thing in the process of using key or password symmetric encryption. is the initialization vector (IV). IV is used in the original encoding (encryption or decryption). In all symmetric algorithm classes we have a property called mode. This is used by IV. If we set the Mode property to CIPHERMODE.CBC (Cipher block chaining), then this pattern is used, and each block of data is processed using the value from the previous chunk. It means that if the system is working on the third block of data, it takes some information from the second block (processing the third block of data). It then takes the information from the first piece of data to process the second block of data. But there is no block available before the first piece of data, so it uses IV to process the first block. This technique ensures that no two identical blocks produce the same output and therefore makes the data more secure.However, if you make MODE=CIPHERMODER.ECB (Electronic codebook mode), then he will not use the above method (using the block in front of the processing to process the blocks behind). This method is useful to you if you want to process a lot of information with very little resources and time. He can also get you to start with the middle of the data. In this case, we include two very important things in symmetric encryption. They are the key and initialization vectors. Now let's look at what algorithms are supported by symmetric cryptography. Symmetric algorithms and symmetric algorithm classes are the key information for symmetric algorithms and their classes. Algorithm name algorithm class (abstract) valid key size (bit) default key size (bit) default implementation class des des descryptoserviceprovidertripledes TripleDES 128, TripleDES CryptoServiceProviderRC2 RC2 40-128 128 Rc2cryptoserviceproviderrijndael RijnDael 128, 192, 256 256 RijndaelManaged here it is necessary to note that all algorithm classes inherit from the abstract class SymmetricAlgorithm. And you can see that each class supports different key sizes. In the same case, they also support the size of different initialization vectors. As I've just said, all of their classes are abstract, so we can't create any instances of these abstract classes directly. But the SymmetricAlgorithm class (also an abstract class) has a shared method called create to do without worrying about how it is implemented to create a specific instance of a class. It means you can use it in the following way. RC2 mRC2 = RC2. Create (); it returns an instance of the RC2 default implementation for you, without having to worry about how to implement the RC2 class specifically. This technique is useful if you want to be able to share code (possible) by updating the RC2 class implementation later in Microsoft. In that case, your code will automatically adapt to their changes and work correctly. Or maybe in the future RC2 classes are written in managed code, and your code can still accept it. In the same case, you can also use the following statement. RC2 Mcrypto = symmetricalgorithm.create ("RC2"); This can also give you an object that returns a RC2 (default implementation). In this case, you use the Reset Create method to set the parameter to return the object of the algorithm using the name of the algorithm. This create method comes from the SymmetricAlgorithm class andAnd all the other classes that use the symmetric algorithm that I mentioned earlier inherit from SymmetricAlgorithm, so you can find the Create method in all the classes above. It means that if you use Rc2.create ("DES") it can also work and will return an object of DES. However, you cannot use the RC2 class to get the Des object. The mechanism above looks useful. We can use our own algorithms to define our own classes in the same way. But to do this, we have to make some minor changes to the Machine.config file. I don't describe it in detail here. You can refer to Wrox's book on Cryptography for more information. Now let's look at some of the methods and properties in the SymmetricAlgorithm class. BlockSize: The size of the data block processed separately. Large data is divided into small chunks of data, and if the data is smaller than the block size, it is appended (with some default values). Key: The key will be used when processing the data. This key is configured to use a byte array. IV: The initialization vector (described above) is used for data processing. Configured as a byte array. KeySize: The size of all bits of the key. Legalblocksize: Returning an enumeration of BlockSize tells you the size of a block that includes the maximum, minimum, and jump values. The jump value means that there are still many values that should be added to the judgment to be worth the next value. For example, if the minimum value is 32, the jump value is 16 so the next judgment value is 48,64 and so on. (Returns The BlockSize enumeration abound tells you legal values for block size including max value, Min value and Skip val Ue. Skip value means that how much value should is added to the last legal value to get next value. Like if min value are and skipvalue is, it means next legal values would be, and, and, mode: The bitwise operation Gets or sets the pattern. See description above. The value is one of the Ciphermode enumerations. Padding: Gets or sets an append value in the Paddingmode enumeration. (empty area of a filler block) Legalkeysize: like Legalblocksize, butis to deal with the keysize. Create: An instance of a class that is created using the default algorithm implementation, as described above. CreateEncryptor: Returns a ICryptoTransform object that can manually encrypt data. will be carefully described in a minute. CreateDecryptor: Returns a ICryptoTransform object that can manually decrypt the data. will be carefully described in a minute. Generatrkey and GenerateIV: If key and IV are null during encryption or decryption, these methods can produce the default key and IV. Vaildkeysize: Checks whether the given key is a valid key for the algorithm. Clear: Clears and eliminates all resources and memory information like keys and IV. Before writing the code, let's say a few things that help us understand the code very well. The CreateEncryptor and CreateDecryptor methods of the CreateEncryptor and Createdecryptorsymmetricalgorithm classes return the ICryptoTransform object. ICryptoTransform is an interface that is implemented by a class that wants to handle a block of data. This process can be encrypted, decrypted, hashed, encoded and decoded based on 64, and so on. The basic purpose of this interface is to complete the data processing chunking (the basic purpose of this Interface was to perform blockwize 處理 of data.). You can use its example directly, but in most cases, for convenience, we do it through other name CryptoStream. Let's look at an example of how to use it. Des mCrypt = new Symmetricalgorithm.create ("des"); ICryptoTransform mtransform = Mcrypt.createencryptot (); CreateEncryptor or CreateDecryptor is a two-cut method. If you do not have any parameters to pass in, then the default key and IV (using the GenerateKey and GenerateIV methods in the Symmetricalgoruthm Class) will be used. On the other hand, you can pass in an IV and key to CreateEncryptor and CreateDecryptor objects. So that encryption and decryption will use our own defined IV and key. CryptoStream class CryptostreaThe M class is typically used to read and write data and to encrypt or decrypt data while reading or writing. It is simple to wrap up the original stream class stream. It uses the buffered access taking all worries from in-manage buffer, block sizes, padding etc. you can use the following code to get an instance of it. Des MCrypt = symmetricalgorithm.create ("des"); ICryptoTransform mtransform = Mcrypt.createencryptor (); CryptoStream mstream = new CryptoStream (filestream,mtransform,cryptostrammode.read) FileStream is a stream (or MemoryStream) that requests an original file that reads data from a hard disk or in memory. Now read and write data by using the Mstream object and the Streamreader/streamwriter object. When you are going to read and write, your encrypted decryption information will depend on the ICryptoTransform object. Code example now we have enough information about SymmetricAlgorithm. Finally, let's look at the snippet of code that will encode and decode. I assume you have a form that contains txtdata and command button controls. Write the following code in the command button's code event. This code will encrypt the text inside the textbox and display it in MessageBox, writing the result back into the textbox. SymmetricAlgorithm Mcryptprov; MemoryStream mmemstr;//Encrypt the data in txtdata and then display the encrypted results in MessageBox and write back to the textbox//Here you can configure any. NET Supported class des Mcryptprov = Symmetricalgorithm.create ("Rijndael");/encrypted data will be stored in memory as a stream so we need the memory Stream object MMEMSTR = new MemoryStream ();//Create Icrypttransform object. (Here we use the default key and the initial vector). Icrypttramsform mtransform = Mcryptprov.createencryptor (); CryptoStream mCswriter = new CryptoStream (mmemstr,mtransform,cryptostreammode.write); StreamWriter mswriter = StreamWriter (mcswriter); Mswriter.writer (This.txtData.Text); Mswriter.flush (); Mcswriter.flushfinalblock (); One thing to note here is that we have not used IV and keys anywhere in the code. In fact, when we don't specify them in the code. NET Framework will be automatically generated for us. However, the example code contained in this article uses the user-specified key and IV. We write encrypted data using MemoryStream in memory. Now let's get the code for the data from memory. The data has been written to memory but we need to echo it back into the textbox and MessageBox, so do the work below. Creates 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 is: \ n" +mencdata); This.txtData.Text = Mencdata; conversion from byte to string must be encoded. I used utf8encoding here. Finally, let's show the decrypted data again in MessageBox and TextBox. Now let's get the decrypted data from memory//Because our data is in memory, so we need to reuse the MemoryStream object. Place the memory point 0mmemstr.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.txtData.Text = Mdecdata; This is all work. We use the same memory stream to decrypt those data. In order to be able to read data from the stream's actually part we first set it to start. Then we create the ICryptoTransform object using the CreateDecryptor method of the SymmetricAlgorithm object. We reused the object (MMEMSTR) in the above code to decrypt it. You can create new objects (using new variables). Then we need to StreamReader the object in order to read the data from memory. While reading that it'll also decrypt that data since we passed CryptoStream object during the creation of StreamReader The last word. NET provides us with a very good managed path to protect our data. We can use. NET to encrypt our data. Although many of the classes still use crypto APIs, we use the old crypto APIs without any problems. But we can use these classes safely without worrying about the specific implementations of those classes. In the following article I will describe the myths and uses of asymmetric cryptographic algorithms. The example code for this article allows you to select an algorithm to encrypt or decrypt the data. And it lets you specify your own IV and key. Code works in two ways. One is a textbox, meaning that you write something in the textbox and then encrypt or decrypt the content. Second, you can choose which files to encrypt or decrypt. To force (0 Votes) Tempted (0 Votes) nonsense (0 Votes) Professional (0 Votes) The title party (0 Votes) passing (0 votes) in the original: NET key (password) Learn-symmetric encryption return to network security home

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.