Back to Blog listturn. NET encryption and decryptionLi Chaoqiang
- Release time: 2015/11/23 12:55
- READ:
- Favorites: 3
- Likes: 0
- Comments: 0
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.
Encryption and decryption
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 message. 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.
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:
- 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).
- The receiver of the message can determine who sent the message (the recipient of the message can determine the sender of the message).
- The receiver of the message can determine that the message has not been tampered with (the integrity of the message must be acknowledged).
Encryption is usually divided into two ways: symmetric and asymmetric, and then we'll look at symmetric cryptography.
Symmetric encryption
The idea of symmetric encryption is very simple, which is to have something called a key that encrypts the message before it is sent and decrypts it with the same key after the message is received. According to the key to generate the encrypted message (ciphertext) of this process, by the encryption algorithm to complete, encryption algorithm is usually public. Its flow is as follows:
- The sender encrypts the message using a key.
- The receiving party decrypts the message using the same key.
You can use the following diagram to represent:
There are two problems with symmetric cryptography:
- 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?
- 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.
In order to solve the above two problems, we need to introduce asymmetric encryption.
Back to top asymmetric encryption
Both the receiver and the sender of the asymmetric encryption hold two keys, one is public, called the public key, and one is self-safekeeping, called the private key. An asymmetric encryption rule is a 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. 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.
The first mode uses only the receiver's public and private keys, known as encryption mode.
Encryption mode
In cryptographic mode, the recipient 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:
- The sender uses the recipient's public key to encrypt the message and then sends it.
- The receiver decrypts the message with its own private key.
You can use the following image to describe:
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: 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).
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 message can determine who sent the message (the recipient of the message can determine the sender of the message).
This problem can be solved in the authentication mode below.
Authentication Mode
In authentication mode, the sender 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:
- The sender encrypts the message with his private key and sends it.
- The receiver decrypts the message using the sender's public key.
You can use the following diagram to express:
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.
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, 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.
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.
Digital signature back to the top of the basic implementation
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 digest of the Message (Digest).
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:
- The sender makes a hash operation of the message that it wants to pass and gets the message digest.
- The sender encrypts the digest with its own private key and sends the message and the encrypted digest to the receiver.
- The receiver uses the sender's public key to decrypt the message and message digest (confirming the sender).
- The receiving party hashes the received message and gets a message digest.
- 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.
This process can be expressed in the following diagram:
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 only encrypts the message digest and does not encrypt the message itself. 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.
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.
Back to top of the advanced implementation
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 sender needs to perform:
- The message is hashed to get a message digest.
- Encrypt the message digest with your own private key (authentication mode: Ensures that the receiver can confirm itself).
- The message is encrypted using the receiver's public key (encryption mode: ensures that the message can only be decrypted by the intended recipient).
- Sends a message and a message digest.
Now let's take a look at the steps the receiver takes:
- The message digest is decrypted with the sender's public key (confirming who sent the message).
- Use your own private key to decrypt the message (securely obtaining the information that is actually available).
- Hashes the message to get a message digest.
- 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).
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.
Back to the top of the certificate mechanism
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 impartial third party, when a party wants to publish the public key, it submits its own identity information 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 a certificate (Certificate). And this impartial third party, is often said the certification authority (Certificate Authority). When we need to get the public key, we just need to get its certificate and extract the public key from it.
. NET encryption decryption support back to top symmetric encryption and decryption
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:
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:
- Create an instance of TripleDESCryptoServiceProvider first, such as the name provider.
- 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[].
- 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.
- 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. Therefore, the. 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. Then there must be a mediator that transforms the plaintext stream into a ciphertext stream, or converts the ciphertext stream to a clear stream. NET is also a stream type, called CryptoStream, to perform this operation. Its constructor is as follows, with a total of three parameters:
Public CryptoStream (Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
- 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.
- 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.
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:
1 Public classCryptohelper2 {3 4 //symmetric cryptographic algorithm provider5 PrivateICryptoTransform encryptor;//Crypto Object6 PrivateICryptoTransform decryptor;//Decryption Object7 Private Const intBufferSize =1024x768;8 9 PublicCryptohelper (stringAlgorithmname,stringkey)Ten { OneSymmetricAlgorithm Provider =symmetricalgorithm.create (algorithmname); AProvider. Key =Encoding.UTF8.GetBytes (key); -PROVIDER.IV =New byte[] {0x12,0x34,0x56,0x78,0x90,0xAB,0xCD,0xEF }; - theEncryptor =provider. CreateEncryptor (); -Decryptor =provider. CreateDecryptor (); - } - + PublicCryptohelper (stringKey): This("TripleDES", Key) { } - + //Encryption Algorithm A Public stringEncrypt (stringcleartext) at { - //create a clear flow - byte[] Clearbuffer =Encoding.UTF8.GetBytes (cleartext); -MemoryStream ClearStream =NewMemoryStream (clearbuffer); - - //create an empty ciphertext stream inMemoryStream Encryptedstream =NewMemoryStream (); - toCryptoStream CryptoStream = + NewCryptoStream (Encryptedstream, Encryptor, cryptostreammode.write); - the //write plaintext stream to buffer * //writes data from buffer to CryptoStream $ intBytesread =0;Panax Notoginseng byte[] buffer =New byte[buffersize]; - Do the { +Bytesread = clearstream.read (buffer,0, buffersize); ACryptostream.write (Buffer,0, bytesread); the} while(Bytesread >0); + - Cryptostream.flushfinalblock (); $ $ //gets the encrypted text -Buffer =Encryptedstream.toarray (); - stringEncryptedtext =convert.tobase64string (buffer); the returnEncryptedtext; - }Wuyi the //Decryption Algorithm - Public stringDecrypt (stringencryptedtext) Wu { - byte[] Encryptedbuffer =convert.frombase64string (encryptedtext); AboutStream Encryptedstream =NewMemoryStream (encryptedbuffer); $ -MemoryStream ClearStream =NewMemoryStream (); -CryptoStream CryptoStream = - NewCryptoStream (Encryptedstream, Decryptor, cryptostreammode.read); A + intBytesread =0; the byte[] buffer =New byte[buffersize]; - $ Do the { theBytesread = cryptostream.read (buffer,0, buffersize); theClearstream.write (Buffer,0, bytesread); the} while(Bytesread >0); - inBuffer =Clearstream.getbuffer (); the stringCleartext = theEncoding.UTF8.GetString (Buffer,0, (int) clearstream.length); About the returncleartext; the } the + Public Static stringEncrypt (stringCleartext,stringkey) - { theCryptohelper helper =NewCryptohelper (key);Bayi returnHelper. Encrypt (cleartext); the } the - Public Static stringDecrypt (stringEncryptedtext,stringkey) - { theCryptohelper helper =NewCryptohelper (key); the returnHelper. Decrypt (encryptedtext); the } the}
This class carries out a simple test:
stringKey ="Abcdefghijklmnop"; stringCleartext ="Welcome to visit Www.tracefact.net"; Cryptohelper Helper=NewCryptohelper (key); stringEncryptedtext =Helper. Encrypt (cleartext); Console.WriteLine (Encryptedtext); Cleartext=Cryptohelper.decrypt (Encryptedtext, key); Console.WriteLine (cleartext); Console.readkey (true);
Reprinted from: http://my.oschina.net/lichaoqiang/blog/534173
. NET encryption and decryption