. NET encryption and decryption

Source: Internet
Author: User
Tags decrypt md5 encryption asymmetric encryption
<span id="Label3"></p>. NET encryption and decryption introduction<p><p>In some of the more important scenarios, passing data over the network requires encryption to ensure Security. This article will briefly describe some of the concepts of encryption and decryption, as well as the associated digital signatures, certificates, and finally, how To. NET for symmetric encryption and decryption of Data.</p></p>Encryption and decryption<p><p>When it comes to encryption, perhaps we are most familiar with is MD5, remember a few years ago when I first started to contact the Web programming, the study of an ASP forum program, its user password is the use of MD5 Encryption. MD5 is actually just a hashing operation, or can be called unidirectional encryption, which means that plaintext (the original Data) cannot be deduced based on ciphertext (encrypted data). What we want to explain below is that we can decrypt and restore the data after the Encryption. For the object to be encrypted, some people are called the message, some people call it data, some people call it information, in order to avoid confusion, in the later part of this article, I unify it as a <strong>message</strong> . So what is encryption? Encryption is the ability to encode messages to create a secure way to communicate, so that only you and the recipients you expect will understand.</p></p><p><p>So how can we call it security? Messages are securely passed on both the receiver and the sender, typically to meet the following three points:</p></p> <ol> <ol> <li>The sender of the message is able to determine that the message is only intended to be decrypted by the receiving party (there is no guarantee that third parties cannot obtain it, but that third parties cannot decrypt it).</li> <li>The receiver of the message can determine who sent the message (the recipient of the message can determine the sender of the message).</li> <li>The receiver of the message can determine that the message has not been tampered with (the integrity of the message must be acknowledged).</li> </ol> </ol><p><p>Encryption is usually divided into two ways: symmetric and asymmetric, and then we'll look at symmetric cryptography.</p></p>Symmetric encryption<p><p>The idea of symmetric encryption is very simple, which is <strong></strong> to have something called a key that encrypts the message before it is sent and decrypts it with <strong>the same</strong> key after the message is Received. According to the key to generate the encrypted message (ciphertext) of this process, by the <strong>encryption algorithm</strong> to complete <strong>,</strong> encryption algorithm is usually PUBLIC. Its flow is as Follows:</p></p> <ol> <ol> <li>The sender encrypts the message using a key.</li> <li>The receiving party decrypts the message using the same key.</li> </ol> </ol><p><p>You can use the following diagram to Represent:</p></p><p><p></p></p><p><p>There are two problems with symmetric cryptography:</p></p> <ol> <ol> <li>Although a key can be used to ensure that messages are delivered securely, How do you ensure that the keys are securely delivered? Because the sender and receiver always have an initial communication to pass the key, how is security guaranteed at this time?</li> <li>The recipient can decrypt the message based on the key, but because of the problem above, the message is likely to be sent by a third party (illegally acquiring the Key) and the receiver cannot discern it.</li> </ol> </ol><p><p>In order to solve the above two problems, we need to introduce asymmetric encryption.</p></p>Asymmetric encryption<p><p>Both the <strong>receiver and the sender</strong> of the asymmetric encryption hold two keys, one is public, called the <strong>public key</strong> , and one is self-safekeeping, called the <strong>private key</strong> . An asymmetric encryption rule is a <strong>message that is encrypted by the public key of a person, and can only be decrypted by the private key of a; the message encrypted by A's private key can only be decrypted by the public key of A. </strong>at this point we can draw the receiver, the sender has two public key two private key four keys, we first look at two simple ways, both of which are only using two Keys.</p></p><p><p>The first mode uses only the Receiver's public and private keys, known as encryption Mode.</p></p>Encryption mode<p><p>In cryptographic mode, the <strong>recipient</strong> of the message publishes the public key and holds the private key. For example, the sender wants to send the message "hello,jimmy" to the receiver, and its steps are:</p></p> <ol> <ol> <li>The sender uses the Recipient's public key to encrypt the message and then sends it.</li> <li>The receiver decrypts the message with its own private key.</li> </ol> </ol><p><p>You can use the following image to Describe:</p></p><p><p></p></p><p><p>In this mode, if a third party intercepts a message from the sender because he doesn't have the Recipient's private key, the message doesn't make sense to Him. It can be seen that it meets the key point of the message security delivery at the beginning of this article: <strong>the sender of the message is able to determine that the message is only intended to be decrypted by the receiving party (it is not guaranteed that third parties cannot obtain it, but that third parties cannot decrypt It)</strong>.</p></p><p><p>In addition, because the Receiver's public key is public, anyone can use the public key to encrypt the message and go to the receiver, and the receiver cannot discriminate the message and know who sent it. so, It doesn't meet the message we're starting to put Forward. two: the receiver of the <strong>message can determine who sent the message (the recipient of the message can determine the sender of the message). </strong></p></p><p><p>This problem can be solved in the authentication mode BELOW.</p></p>Authentication Mode<p><p>In authentication mode, the <strong>sender</strong> of the message publishes the public key and holds the private key. For example, the sender wants to send the message "Welcome to tracefact.net" to the receiver, and its steps are:</p></p> <ol> <ol> <li>The sender encrypts the message with his private key and sends it.</li> <li>The receiver decrypts the message using the Sender's public key.</li> </ol> </ol><p><p>You can use the following diagram to Express:</p></p><p><p></p></p><p><p>In this mode, if the sender is called ken, the receiver is called matthew, because Matthew can only use Ken's public key to decrypt the message, and cannot use molly, sandy, or any other Person's public key to decrypt the Message. So he must be able to make sure that the message was sent by Ken. therefore, this pattern satisfies the key point two of the message security passed Forward.</p></p><p><p>At the same time, because Ken's public key is public, any third party that intercepts the message can use Ken's public key to decrypt the message, in other words, <strong></strong> the message is now Unsafe. therefore, In contrast to the encryption mode, it does not meet the key point of the message security pass that was presented Earlier.</p></p><p><p>Regardless of whether the encryption mode or authentication mode, does not solve the encryption and decryption of the key three: the receiver must be able to confirm that the message has not been changed. To solve this problem, a digital signature is Introduced.</p></p>Basic implementation of digital signature<p><p>Digital signature is actually the above asymmetric encryption authentication mode, but did a little bit of improvement, added hash algorithm. We are more familiar with the hashing algorithm may be MD5, many Open-source forums have adopted this ALGORITHM. Hashing algorithm has three characteristics: one is irreversible, from the results can not be deduced from the original data; the second is that the original data, even if the little change, will make the hash value changes greatly; third, no matter how large or how little data, there is always a fixed-length hash value (common 32-bit 64-bit). The resulting hash value is often referred to as a <strong>digest</strong> of the message (digest).</p></p><p><p>So how to ensure the integrity of the data by introducing a hash function? That is, the receiver is able to confirm that the message was actually sent by the sender, and that it was not modified Halfway. The specific process is as follows:</p></p> <ol> <ol> <li>The sender makes a hash operation of the message that it wants to pass and gets the message Digest.</li> <li>The sender encrypts the digest with its own private key and sends the message and the encrypted digest to the Receiver.</li> <li>The receiver uses the Sender's public key to decrypt the message and message digest (confirming the sender).</li> <li>The receiving party hashes the received message and gets a message Digest.</li> <li>The receiver compares the message digest obtained in the previous step with the message digest sent by the Sender. If the same, the message has not been changed, and if different, the message has been tampered With.</li> </ol> </ol><p><p>This process can be expressed in the following diagram:</p></p><p><p></p></p><p><p>As we can see, the digital signature strengthens the authentication mode of asymmetric encryption by introducing hashing algorithm, which ensures the integrity of the Message. In addition, notice that the asymmetric encryption algorithm above <strong>only encrypts the message digest and does not encrypt the message itself</strong> . Asymmetric encryption is a very time-consuming operation that can significantly increase the execution speed of a program because it encrypts only the message digest, resulting in a significant reduction in computational computation. At the same time, it still does not ensure that the message is not intercepted by a third party, not only that, because the message is delivered in clear text, the third party does not even need the Sender's public key, You can view the message directly.</p></p><p><p>In order to solve this problem, it is only necessary to combine the authentication mode, encryption mode and message digest of asymmetric encryption, which is the advanced mode below.</p></p>Advanced implementations<p><p>Since this process is slightly more complex than the above, we divide it into two parts: sender and Receiver. First look at the steps the <strong>sender</strong> needs to perform:</p></p> <ol> <ol> <li>The message is hashed to get a message Digest.</li> <li>Encrypt the message digest with your own private key (authentication mode: ensures that the receiver can confirm itself).</li> <li>The message is encrypted using the Receiver's public key (encryption mode: ensures that the message can only be decrypted by the intended recipient).</li> <li>Sends a message and a message Digest.</li> </ol> </ol><p><p>Now let's take a look at the steps the receiver Takes:</p></p> <ol> <ol> <li>The message digest is decrypted with the Sender's public key (confirming who sent the message).</li> <li>Use your own private key to decrypt the message (securely obtaining the information that is actually available).</li> <li>Hashes the message to get a message Digest.</li> <li>Compares the message digest obtained in the previous step with the message digest that was decrypted in the first step (confirming that the message was tampered with).</li> </ol> </ol><p><p>As can be seen in this way, the receiver, the sender of all the four keys, and the use of the message digest, so that all three of the previously proposed security pass all the conditions are Satisfied. So is this the best way to do it? no, because We've already said that asymmetric encryption is a time-consuming operation, so this scheme is Inefficient. In fact, we can solve the problem of the key transmission in symmetric encryption, if you have forgotten can turn to the front to see, that is, we can use the high-level implementation of this method to the symmetric encryption of the key transfer, for the actual data passing, the use of symmetric encryption to complete, Because It's safe now.</p></p>Certificate mechanism<p><p>A concept related to digital signatures is the certificate mechanism, what is the certificate used to do? In the various modes above, we have always used the assumption that the recipient or Sender's public key is always correct (it is actually the other Party's announcement). In fact, unless the other hand hands the public key to us, if not to take action, the two sides in the network to pass the public key, the same can be tampered with. So how do we solve this problem? A certificate mechanism is required: it is possible to introduce an <strong>impartial</strong> third party, when a party wants to publish the public key, it submits its own identity and public key to the third party, the third party confirms its identity and, if there is no problem, packages its information and public key into <strong> Certificate (Certificate)</strong>. And this impartial third party, is often said the <strong>certification Authority (Certificate Authority)</strong>. When we need to get the public key, we just need to get its certificate and extract the public key from it.</p></p>. NET encryption and decryption support symmetric encryption and decryption<p><p>I believe that through the previous pages of the narrative, we have understood the encryption and decryption, digital signature of the basic principles, we look at the Following. NET is how to support encryption and Decryption. As we have done in the classification above,. NET also provides two sets of classes for cryptographic decryption, one for symmetric encryption, and one for asymmetric encryption, as shown in:</p></p><p><p></p></p><p><p>The above class can also be divided into two groups by name, a set of suffixes of "cryptoserviceprovider", is for the underlying Windows API wrapper class, a set of suffixes "Managed", is The. The newly written class in Net. Now suppose we use TripleDES as the algorithm, then the encryption process is as Follows:</p></p> <ol> <ol> <ol> <li>Create an instance of TripleDESCryptoServiceProvider first, such as the name Provider.</li> <li>Specify the key and IV on provider, which is its key property and IV Property. Here's A brief explanation of IV (initialization vector), if a string (or Data) is encrypted before many parts are duplicated such as abcabcabc, then after the encryption, although the string is garbled, but the relevant parts are also Duplicated. In order to solve this problem, the IV was introduced, and when it was used, even the repetition was disrupted after the Encryption. For a particular algorithm, the value of the key and IV can be arbitrarily specified, but the length is fixed, usually the key is 128-bit or 196-bit, and the IV is 64 BITS. Both the key and IV are byte[] types, so if you use the encoding class to convert a string to byte[], then the encoding is important because UTF8 is a variable-length encoding, so for Chinese and english, you need to pay special attention to the length of byte[].</li> <li>If it is encrypted, the CreateEncryptor () method is used in provider to create an icryptotransform type of cipher object, and if it is decrypted, the CreateDecryptor () method is raised in provider, The same is the creation of a icryptotransform type of decryption Object. ICryptoTransform defines the operation of the cryptographic Transformation. NET will invoke this interface at the BOTTOM.</li> <li>Because streams and byte[] are data type-independent data structures that can save and transmit any form of information, the difference is just byte[] is a static concept and the flow is a dynamic concept. So. NET uses a stream of encryption and decryption, we can think of there are two streams, one is the plaintext stream, containing the data before encryption, one is a ciphertext stream, containing encrypted Data. <strong>Then there must be a mediator that transforms the plaintext stream into a ciphertext stream, or converts the ciphertext stream into a clear stream. </strong>. NET is also a stream type, called cryptostream, to perform this Operation. Its constructor is as follows, with a total of three parameters:</li> </ol> </ol> </ol><p class="Code"><p class="Code">Public CryptoStream (stream stream, icryptotransform transform, cryptostreammode Mode)</p></p> <ol> <ol> <li>When encrypted, the stream is a ciphertext stream (note that at this time the ciphertext stream does not contain data, just an empty stream); icryptotransform is the 3rd step to create the cipher, containing the encryption algorithm; CryptoStreamMode enumeration is write, This means that the plaintext stream flowing through the CryptoStream is written to the ciphertext Stream. finally, the encrypted data is obtained from the ciphertext Stream.</li> <li>When decrypting, the stream is a ciphertext stream (at which time the ciphertext stream contains data); ICryptoTransform is the 3rd step to create the decryption, containing the decryption algorithm; CryptoStreamMode enumeration is read, meaning that the data in the ciphertext stream is read out into the byte[] array , which is then converted from byte[] to clear text stream, clear Text string.</li> </ol> </ol><p><p>As can be seen, CryptoStream always accepts ciphertext streams and, depending on the value of the CryptoStreamMode enumeration, determines whether the plaintext stream is written to the ciphertext stream (encrypted) or the ciphertext stream is read into the plaintext stream (decryption). Here's a helper class I've written to encrypt and decrypt:</p></p><p class="Code">Symmetric encryption Helper Class<br>public class Cryptohelper {<br><br>Symmetric cryptographic algorithm Provider<br>Private ICryptoTransform encryptor; Crypto object<br>Private ICryptoTransform decryptor; Decryption Object<br>Private Const int buffersize = 1024;<br><br>Public cryptohelper (string algorithmname, string Key) {<br>SymmetricAlgorithm Provider = Symmetricalgorithm.create (algorithmname);<br>Provider. Key = Encoding.UTF8.GetBytes (key);<br>PROVIDER.IV = new byte[] {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};<br><br>Encryptor = Provider. CreateEncryptor ();<br>Decryptor = Provider. CreateDecryptor ();<br>}<br><br>Public Cryptohelper (string key): this ("TripleDES", key) {}<br><br>Encryption algorithm<br>public string Encrypt (string Cleartext) {<br>Create a clear flow<br>byte[] Clearbuffer = Encoding.UTF8.GetBytes (cleartext);<br>MemoryStream clearStream = new MemoryStream (clearbuffer);<br><br>Create an empty ciphertext stream<br>MemoryStream encryptedstream = new MemoryStream ();<br><br>CryptoStream CryptoStream =<br>New CryptoStream (encryptedstream, encryptor, cryptostreammode.write);<br><br>Write plaintext stream to buffer<br>Writes data from buffer to CryptoStream<br>int bytesread = 0;<br>byte[] buffer = new byte[buffersize];<br>do {<br>Bytesread = Clearstream.read (buffer, 0, buffersize);<br>Cryptostream.write (buffer, 0, bytesread);<br>} while (bytesread > 0);<br><br>Cryptostream.flushfinalblock ();<br><br>Gets the encrypted text<br>Buffer = Encryptedstream.toarray ();<br>String encryptedtext = Convert.tobase64string (buffer);<br>Return encryptedtext;<br>}<br><br>Decryption algorithm<br>public string Decrypt (string Encryptedtext) {<br>byte[] Encryptedbuffer = convert.frombase64string (encryptedtext);<br>Stream encryptedstream = new MemoryStream (encryptedbuffer);<br><br>MemoryStream clearStream = new MemoryStream ();<br>CryptoStream CryptoStream =<br>New CryptoStream (encryptedstream, decryptor, cryptostreammode.read);<br><br>int bytesread = 0;<br>byte[] buffer = new byte[buffersize];<br><br>do {<br>Bytesread = Cryptostream.read (buffer, 0, buffersize);<br>Clearstream.write (buffer, 0, bytesread);<br>} while (bytesread > 0);<br><br>Buffer = Clearstream.getbuffer ();<br>String cleartext =<br>Encoding.UTF8.GetString (buffer, 0, (int) clearstream.length);<br><br>Return cleartext;<br>}<br><br>public static string Encrypt (string cleartext, string Key) {<br>Cryptohelper helper = new Cryptohelper (key);<br>Return Helper. Encrypt (cleartext);<br>}<br><br>public static string Decrypt (string encryptedtext, string Key) {<br>Cryptohelper helper = new Cryptohelper (key);<br>Return Helper. Decrypt (encryptedtext);<br>}<br>}</p><p><p>We can do a simple test of the above class:</p></p><p class="Code"><p class="Code">static void Main (string[] Args) {<br>String key = "abcdefghijklmnop";<br>String cleartext = "welcome to www.tracefact.net";<br><br>Cryptohelper helper = new Cryptohelper (key);<br><br>String encryptedtext = Helper. Encrypt (cleartext);<br>Console.WriteLine (encryptedtext);<br><br>cleartext = Cryptohelper.decrypt (encryptedtext, key);<br>Console.WriteLine (cleartext);<br>}</p></p><p><p>You should see the following output:</p></p><p><p></p></p>Summarize<p><p>First of all to apologize, I did not write. NET Non-symmetric encryption part, because I rarely use, so this Part I am not very familiar with, but the principle should now be very clear, I want to wait until the need to learn how to use Them. By that time, I would have updated this article again. Through this article, I believe that the encryption, decryption, digital signature and other security aspects of the concept has a preliminary understanding, but also learned how To. NET for symmetric Encryption.</p></p><p><p>Thanks for reading, I hope this article can bring you help!</p></p><p><p>. NET encryption and decryption</p></p></span>

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.