Encryption and decryption technology in. net

Source: Internet
Author: User
Tags asymmetric encryption
Document directory
  • Symmetric encryption
  • Asymmetric encryption
  • Basic implementation
  • Advanced implementation
  • Certificate Mechanism
  • Symmetric encryption and decryption

I recently read an article written by Zhang Ziyang. The encryption and decryption technology in. NET is very good and reprinted.

Reprinted address is http://www.cnblogs.com/JimmyZhang/archive/2008/10/02/Cryptograph.html

Introduction to encryption and decryption in. net

In some important application scenarios, data transmission over the network needs to be encrypted to ensure security. This article briefly introduces some concepts of encryption and decryption, as well as related digital signatures and certificates, and finally introduces how to perform symmetric encryption and decryption on data in. net.

Encryption and decryption

When it comes to encryption, MD5 is probably the most familiar one. I remember an ASP Forum program I studied when I first started to use web programming a few years ago, its user password is encrypted using MD5. MD5 is actually a hash operation, or it can be called one-way encryption, that is, the plaintext (original data) cannot be exported Based on the ciphertext (encrypted data ). What we should note below is that data can be decrypted and restored after encryption. For objects to be encrypted, some are called messages, some are called data, and some are called information. To avoid confusion, I will refer to themMessage. So what is encryption? Encryption creates a secure communication mode by encoding messages so that only you and the expected receiver can understand them.

So how can we call it security? Messages are transmitted securely between the recipient and the sender. the following three key points must be met:

  1. The sender of the message can determine that only the expected receiver can decrypt the message (the third party cannot obtain the message, but the third party cannot decrypt the message ).
  2. The receiver of the message can determine who sent the message (the receiver of the message can determine the sender of the message ).
  3. The receiver of the message can determine that the message has not been tampered with on the way (the message integrity must be confirmed ).

Encryption is usually divided into two methods: symmetric encryption and asymmetric encryption. Next we will first look at symmetric encryption.

Symmetric encryption

The idea of symmetric encryption is very simple.KeyBefore the message is sent, use the key to encrypt the message. After the recipient receives the message, useSameKey. The process of generating encrypted messages (ciphertext) based on the key.Encryption AlgorithmTo complete,Encryption algorithms are usually public. The process is as follows:

  1. The sender uses the key to encrypt the message.
  2. The recipient decrypts the message using the same key.

You can use the following figure to represent it:

Symmetric encryption has two problems:

  1. Although the key can be used to ensure secure transmission of messages, how can we ensure secure transmission of keys? Because the sender and receiver always have an initial communication to transmit the key, how can we ensure the security at this time?
  2. Although the recipient can decrypt the message based on the key, the message may be sent by a third party (illegally obtaining the key) due to the above problem, and the recipient cannot identify the message.

To solve the above two problems, we need to introduce asymmetric encryption.

Asymmetric encryption

Asymmetric encryptionReceiver and senderBoth of them hold two keys. One is open to the outside world and is calledPublic Key, One is self-managed, calledPrivate Key. The asymmetric encryption rule isMessages encrypted by a's public key can only be decrypted by a's private key. Messages encrypted by a's private key can only be decrypted by a's public key.In this case, we can conclude that the receiver and sender have two public keys and two private keys. Let's take a look at two simple methods, both of which use only two keys.

The first mode only uses the public key and private key of the receiver, which is called the encryption mode.

Encryption Mode

In encryption modeReceiverPublish the public key and hold the private key. For example, if the sender wants to send the message "Hello, Jimmy" to the receiver, the procedure is as follows:

  1. The sender uses the recipient's public key to encrypt the message and then sends the message.
  2. The receiver uses its own private key to decrypt the message.

You can use the following figure to describe:

In this mode, if a third party intercepts the message sent by the sender because the sender does not have the private key of the receiver, the message is meaningless to him. It can be seen that it can satisfy the key points of secure message transfer proposed at the beginning of this article:The sender of the message can determine that only the expected receiver can decrypt the message (the third party cannot obtain the message, but the third party cannot decrypt the message).

In addition, because the public key of the receiver is public, anyone can use this public key to encrypt the message and send it to the receiver. The receiver cannot identify the message, you cannot know who sent the message. Therefore, it does not meet the following key points of secure message transmission:The receiver of the message can determine who sent the message (the receiver of the message can determine the sender of the message ).

This problem can be solved in the following Authentication mode.

Authentication Mode

In Authentication modeSenderPublish the public key and hold the private key. For example, if the sender wants to send the message "Welcome to tracefact.net" to the receiver, the procedure is as follows:

  1. The sender uses his/her own private key to encrypt the message and then sends it.
  2. The recipient decrypts the message using the sender's public key.

It can be expressed in the following figure:

In this mode, if the sender is called a Ken and the receiver is called Matthew, because Matthew can only decrypt the message using the public key of the Ken, molly, Sandy, or any other person's public key cannot be used to decrypt the message, so he must be able to determine that the message was sent by the Ken. Therefore, this mode satisfies the two key points of secure message transmission.

At the same time, because the public key of the Ken is public, any third party that intercepts the message can use the public key of the Ken to decrypt the message. In other words, the message isInsecure. Therefore, in contrast to the encryption mode, it cannot meet the key aspect of secure message transmission proposed above.

No matter whether the encryption mode or authentication mode is used, key aspect 3 in encryption and decryption is not solved: the receiver must be able to confirm that the message has not been changed. To solve this problem, a digital signature is introduced.

Basic Digital Signature implementation

The digital signature is actually the Authentication Mode in the above asymmetric encryption mode, but a little improvement is made, and the hash algorithm is added. The hash algorithm that everyone is familiar with may be MD5, which is used in many open source forums. Hash algorithms have three features: one is irreversible, and the result cannot be used to calculate the original data; the other is that the original data is slightly changed, the hash value changes greatly. Third, no matter how large or small the data is, a fixed-length hash value is always generated (usually 32-bit and 64-bit ). The generated hash value is usually called the messageSummary(Digest ).

So how can we ensure data integrity by introducing hash functions? That is, the receiver can confirm that the message is sent by the sender, but has not been modified in the middle. The specific process is as follows:

  1. The sender performs a hash operation on the messages to be transmitted to obtain the message digest.
  2. The sender uses his/her own private key to encrypt the digest and send the message and the encrypted digest to the receiver.
  3. The receiver decrypts the message and message digest using the sender's public key (the sender is confirmed ).
  4. The Receiver performs a hash operation on the received message to obtain a message digest.
  5. The receiver compares the message digest obtained in the previous step with the message digest sent by the sender. If they are the same, the message has not been modified. If they are different, the message has been tampered.

This process can be expressed in the following figure:

We can see that by introducing the hash algorithm, the digital signature enhances the asymmetric encryption authentication mode and ensures message integrity. Note that the above asymmetric encryption algorithm,Only the message digest is encrypted, but the message itself is not encrypted.. Asymmetric encryption is a very time-consuming operation. Because only the message digest is encrypted, the calculation workload is greatly reduced, so it can significantly improve the execution speed of the program. 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 transmitted in plaintext, the third party can directly view the message without the sender's public key.

To solve this problem, you only need to combine the asymmetric encryption authentication mode, encryption mode, and message digest. This is the following advanced mode.

Advanced implementation

Since this process is a little more complex than above, we will divide it into two parts: the sender and the receiver. First lookSenderSteps:

  1. Hash the message to obtain the message digest.
  2. Use your own private key to encrypt the message digest (Authentication Mode: ensures that the recipient can confirm himself ).
  3. Use the public key of the receiver to encrypt the message (encryption mode: ensures that the message can only be decrypted by the expected receiver ).
  4. Send messages and message summary.

Next, let's take a look at the steps executed by the receiver:

  1. Decrypt the message digest using the sender's public key (to confirm who sent the message ).
  2. Use your own private key to decrypt the message (securely obtain the actual information ).
  3. Hash messages to obtain message summaries.
  4. Compare the message digest obtained in the previous step with the message digest decrypted in the first step (check whether the message is tampered ).

As you can see, in the above method, all four keys of the receiver and sender are used, and the message digest is used together, so that all the three conditions for safe transmission mentioned above are met. So is this method the best? No, as we have already said, asymmetric encryption is a very time-consuming operation, so this solution is very inefficient. In fact, we can solve the key transfer problem in symmetric encryption through it. If you forget it, you can go to the front and take a look. That is to say, we can use the advanced implementation method here to transmit the key in symmetric encryption. For actual data transmission afterwards, the symmetric encryption method is used, because it is safe now.

Certificate Mechanism

A concept related to digital signature is the certificate mechanism. What is a certificate used? In the above models, we have always used the assumption that the public key held by the receiver or sender and the other party is always correct (indeed published by the other party ). In fact, unless the other party hand over the public key to us, if no action is taken, the two parties may be tampered with when passing the public key in the network. How can this problem be solved? In this case, the certificate mechanism is required: You can introduceFairWhen a third party wants to publish a public key, it submits its own identity information and public key to the third party. The third party confirms its identity. If no problem exists, then, the Information and Public Key are packagedCertificate (certificate). This fair third party is often saidCertificate Authority). When we need to obtain the public key, we only need to obtain its certificate, and then extract the public key from it.

. Net supports symmetric encryption and decryption.

I believe that through the previous pages, we have understood the basic principles of encryption and decryption and digital signature. Let's take a look at how encryption and decryption are supported in. net. As we have classified above,. Net also provides two groups for encryption and decryption, one for symmetric encryption and the other for asymmetric encryption, as shown in:

The above classes can also be divided into two groups by name. One group is suffixed with "cryptoserviceprovider" and is a packaging class for the underlying Windows API. The other group is suffixed with "managed" and is in. net. Assume that we use tripledes as an algorithm, the encryption process is as follows:

  1. Create a tripledescryptoserviceprovider instance. The instance name is provider.
  2. Specify the key and IV on the provider, that is, its key and IV attributes. Here is a brief explanation of IV (initialization vector). If many parts of a string (or data) are duplicated before encryption, such as abcabcabc, after encryption, although the string is garbled, however, the related parts are also repeated. To solve this problem, IV is introduced. When it is used, even repeated encryption is disrupted. For specific algorithms, the key and IV values can be specified at will, but the length is fixed. Generally, the key is 128-bit or 196-bit, and the IV value is 64-bit. Both the key and IV are of the byte [] type. Therefore, if you use the encoding class to convert a string to a byte [], the encoding method is very important because utf8 is a variable-length encoding, pay special attention to the length of byte [] for Chinese and English characters.
  3. For encryption, call the createencryptor () method on the provider to create an icryptotransform-type encryptor object. For decryption, call the createdecryptor () method on the provider, create an icryptotransform-type encryptor object. Icryptotransform defines the encryption conversion operation.. NET will call this interface at the underlying layer.
  4. Because the stream and byte [] are data structures unrelated to the data type, you can save and transmit any form of data, the difference is that byte [] is a static concept, while stream is a dynamic concept. Therefore ,. net uses stream encryption and decryption. We can think of two streams, one is the plaintext stream, which contains the data before encryption; the other is the ciphertext stream, which contains the encrypted data.Then there must be an intermediary who will convert the plaintext flow into the ciphertext flow, or convert the ciphertext flow into the plaintext flow.. NET is also a stream type called cryptostream. Its constructor has the following three parameters:

    Public cryptostream (Stream stream, icryptotransform transform, cryptostreammode Mode)

  5. When encryption is performed, stream is a ciphertext stream (note that the ciphertext Stream does not contain data, but is only an empty stream). icryptotransform is a encryptor created in step 1, including the encryption algorithm; cryptostreammode enumeration is write, which means to write the plaintext stream that flows through cryptostream to the ciphertext stream. Finally, the encrypted data is obtained from the ciphertext stream.
  6. When decryption is performed, stream is the ciphertext stream (at this time, the ciphertext stream contains data); icryptotransform is the decryption tool created in step 1, including the decryption algorithm; cryptostreammode enumeration is read, this means that data in the ciphertext stream is read to the byte [] array, and then converted from byte [] to the plain text stream and plaintext string.

It can be seen that cryptostream always accepts the ciphertext stream and writes the plaintext stream to the ciphertext stream (encrypted) based on the value enumerated by cryptostreammode ), or read the ciphertext stream into the plaintext stream (decryption ). The following is a helper class I have compiled for encryption and decryption:

// Symmetric encryption help class
Public class cryptohelper {

// Provides the symmetric encryption algorithm.
Private icryptotransform encryptor; // encryptor object
Private icryptotransform decryptor; // encryptor object
Private const int buffersize = 1024;

Public cryptohelper (string algorithmname, string key ){
Using ricalgorithm provider = Using ricalgorithm. Create (algorithmname );
Provider. Key = encoding. utf8.getbytes (key );
Provider. IV = new byte [] {0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };

Encryptor = provider. createencryptor ();
Decryptor = provider. createdecryptor ();
}

Public cryptohelper (string key): This ("tripledes", key ){}

// Encryption Algorithm
Public String encrypt (string cleartext ){
// Create a plaintext stream
Byte [] clearbuffer = encoding. utf8.getbytes (cleartext );
Memorystream Clearstream = new memorystream (clearbuffer );

// Create an empty ciphertext stream
Memorystream encryptedstream = new memorystream ();

Cryptostream =
New cryptostream (encryptedstream, encryptor, cryptostreammode. Write );

// Write the plaintext stream into the buffer
// Write data in the buffer to cryptostream
Int bytesread = 0;
Byte [] buffer = new byte [buffersize];
Do {
Bytesread = Clearstream. Read (buffer, 0, buffersize );
Cryptostream. Write (buffer, 0, bytesread );
} While (bytesread> 0 );

Cryptostream. flushfinalblock ();

// Obtain the encrypted text
Buffer = encryptedstream. toarray ();
String encryptedtext = convert. tobase64string (buffer );
Return encryptedtext;
}

// Decryption algorithm
Public String decrypt (string encryptedtext ){
Byte [] encryptedbuffer = convert. frombase64string (encryptedtext );
Stream encryptedstream = new memorystream (encryptedbuffer );

Memorystream Clearstream = new memorystream ();
Cryptostream =
New cryptostream (encryptedstream, decryptor, cryptostreammode. Read );

Int bytesread = 0;
Byte [] buffer = new byte [buffersize];

Do {
Bytesread = cryptostream. Read (buffer, 0, buffersize );
Clearstream. Write (buffer, 0, bytesread );
} While (bytesread> 0 );

Buffer = Clearstream. getbuffer ();
String cleartext =
Encoding. utf8.getstring (buffer, 0, (INT) Clearstream. Length );

Return cleartext;
}

Public static string encrypt (string cleartext, string key ){
Cryptohelper helper = new cryptohelper (key );
Return helper. Encrypt (cleartext );
}

Public static string decrypt (string encryptedtext, string key ){
Cryptohelper helper = new cryptohelper (key );
Return helper. decrypt (encryptedtext );
}
}

We can perform a simple test on the above class:

Static void Main (String [] ARGs ){
String key = "abcdefghijklmnop ";
String cleartext = "Welcome to www.tracefact.net ";

Cryptohelper helper = new cryptohelper (key );

String encryptedtext = helper. Encrypt (cleartext );
Console. writeline (encryptedtext );

Cleartext = cryptohelper. decrypt (encryptedtext, key );
Console. writeline (cleartext );
}

The following output result is displayed:

Summary

Sorry, I did not write it. I am not very familiar with this part of asymmetric encryption in net because it is rarely used, but the principle should be clear now, I want to learn how to use them when necessary. At that time, I will update this article again. Through this article, I believe that everyone has a preliminary understanding of encryption, decryption, digital signature, and other security concepts, and also learned how to perform symmetric encryption under. net.

Thank you for reading this article. I hope this article will help you!

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.