Shenzhen Ka Wah Road _09 _ architect advanced encryption and decryption

I. Introduction

In some of the more important application scenarios, passing data through the network needs to be encrypted to ensure security. This article will briefly introduce some concepts of encryption and decryption, and related digital signatures, certificates, and finally explains how the data is symmetric encryption and decryption in .NET.

1, encryption and decryption

When it comes to encryption, probably most familiar is the MD5, and I remember a few years ago I program ASP forum just getting started with Web programming, research, and it's the user's password is to use the MD5 encryption. In fact only a MD5 hashing, or it may be referred to as a one-way encryption, that is not in accordance with the ciphertext (encrypted data), derive the plaintext (original data). And we have to be explained below, it can be decrypted to restore data after encryption. For objects to be encrypted, and some people called the message, some people called the data, and some people called information, in order to avoid confusion later in this article, I will call it a unified message . So what is it encrypted? Encryption is by encoding a message, establish a secure means of communication, so that only you and your intended recipient can understand.

So how can it be called safe? Secure message transfer receiver and sender, generally satisfy the following three points:

Sender of the message to determine the message that only the intended recipient can decrypt (no guarantee third parties do not obtain, but to ensure that third parties can not be decrypted).

The message recipient can determine who the message is transmitted (message recipient may be determined sender of the message).

The message recipient can determine the way the message has not been tampered (must confirm message integrity).

Encryption is usually divided into two modes: symmetric encryption and asymmetric encryption, let's take a look symmetric encryption.

1.1, symmetric encryption

Symmetric encryption idea is very simple, is referred to it contains a key things, using a key to encrypt the message before the message is sent, after the other received the message, use the same key for decryption. The key process to generate the encrypted message (ciphertext) by the encryption algorithm is done , the encryption algorithm is generally disclosed. Its process is as follows:

The sender uses a key to encrypt the message.

The receiver uses the same key to decrypt the message.

One can use the following diagram to represent:

 

Symmetric encryption there are two problems:

Although it can ensure that key messages are delivered safely, but the key is how to ensure the safe conduct pass? Because the sender and receiver have a total initial communication, used to pass key, how to ensure security at this time?

Although it is possible according to the recipient to decrypt the key message, but because of the above problems, there may be a message by a third party (illegally obtained key) sent, but the recipient can not tell.

In order to solve the above two issues, we need to introduce asymmetric encryption.

1.2 Asymmetric encryption

Asymmetric encryption of the receiver and sender are in possession of two keys, one publicly known as public key , it is a charge himself, called the private key . Asymmetric encryption rules are encrypted with the public key of person A message can only be decrypted by the private key of A; A private key encrypted by the message can be decrypted only by the A's public key. At this point we can draw the recipient, the sender has a total of four two public two private keys, we take a look at two simple ways, these two methods are the only two keys.

The first mode uses only the recipient's public and private keys, called the encryption mode.

Encryption mode

In the encryption mode, the message recipient publish public, private holding. To send a message sender such as "hello, jimmy" to the recipient, it is the step of:

The sender using the recipient's public key to encrypt a message, and then send.

The recipient uses his private key to decrypt the message.

FIG one can use the following be described:

 

In this mode, if a third party intercepts messages sent by the sender, because he did not have the recipient's private key, so this news meant nothing to him. Visible, it can meet the messaging security point of delivery of a paper initially proposed: sender of the message to determine the message that only the intended recipient can decrypt (no guarantee third parties do not obtain, but to ensure that third parties can not be decrypted) .

In addition, because the recipient's public key is public, anyone can use the public key to encrypt the message and sends it to the recipient, and the recipient of a message can not discriminate not know who sent. So, it does not meet the messaging security point we started passing the proposed two: (sender recipient of a message can determine the message) recipient of a message can determine who the message is sent.

This problem can be solved in the following authentication mode.

Authentication Mode

In the authentication mode, the message sender publish public, private holding. To send a message sender such as "Welcome to Tracefact.net" to the recipient, it is the step of:

Sender uses his private key to encrypt the message, then send.

The recipient uses the sender's public key to decrypt the message.

Can be expressed in a following FIG:

 

In this mode, if the sender is called Ken, the recipient is called Matthew, Matthew only because Ken use of public key to decrypt the message, but can not use Molly, Sandy or any other person public key to decrypt the message, so he It will be able to determine the message was sent by Ken to the. Thus, this model satisfies the security elements previously proposed message passing two.

At the same time, because of Ken's public key is published, any third party intercepted the message Ken are able to use the public key to decrypt the message, in other words, the message is now unsafe . Thus, contrary to the encryption mode, it can not meet the security elements passing a message previously proposed.

Regardless of encryption mode or authentication mode, encryption and decryption are not resolved in three points: the receiver must be able to confirm that the message has not been altered. To solve this problem, and the introduction of digital signatures.

1.3, a digital signature

1.3.1, the basic realization

Digital signature is actually on top of the non-symmetric encryption certified mode, just do a little bit of improvement, adding a hash algorithm. We are more familiar with the MD5 hash algorithm is probably a lot of open source forum have adopted this method. Hash algorithm has three characteristics: First, irreversible, can not be deduced from the results of the original data; the second is even a little bit of the original data changes, the hash value will make a huge difference; Third, no matter how big or how small data always produce a fixed-length hash value (common being 32-bit 64-bit). Commonly referred to as a hash value generated message digest (digest).

So how to ensure data integrity it by introducing a hash function? I.e. acknowledgment message recipient can indeed sent by the sender, without being modified in the middle. Specific process is as follows:

Message sender wants to be passed to a hash operation to obtain a message digest.

The sender uses its own private key to encrypt the digest, the digest will be transmitted and the encrypted message to the recipient.

The recipient uses the sender's public key to decrypt the message and the message digest (to confirm the sender).

The recipient of the message received hashed to obtain a message digest.

Obtained in the previous step the recipient of the message digest with the sender sent the message digest for comparison. If the same, indicating that the message has not been modified; if different, then the message has been tampered with.

This process can be expressed in the following FIG one:

 

We can see through the introduction of digital signature hashing algorithm, asymmetric encryption and authentication mode further strengthened to ensure the integrity of the message. In addition, note that the above non-symmetric encryption algorithm, but the message digest is encrypted, but not the message itself is encrypted . Asymmetric encryption is a time-consuming operation, since only the encrypted message digest, such that the amount of computation substantially reduced, so that it is possible to significantly improve the execution speed of the program. At the same time, it still does not ensure that the message is not to be intercepted by a third party, not only that, because the message is passed in clear text, do not even need a third-party sender's public key, you can view messages directly.

To solve this problem, simply asymmetric encryption authentication mode, encryption mode and a message digest binding on it, which is below the advanced mode.

1.3.2, advanced implementation

Since this process is slightly more complicated than the above, we divided into two parts, the sender and receiver of view. Take a look at the sender steps to follow:

The hashed message, obtain the message digest.

Use your own private key to encrypt the message digest (authentication mode: Make sure the recipient can confirm themselves).

Using the recipient's public key to encrypt the message (Encryption Mode: the message can be decrypted only ensure the desired recipient).

Send messages and message digest.

Next we look at the steps executed by the recipient:

Using the sender's public key to decrypt the message digest (who confirmed the message is sent).

Use their private key to decrypt the message (safe access to the actual information to be obtained).

The hashed message, obtain the message digest.

Message digest obtained in the previous step and the first step to decrypt the message digest comparison (to confirm the message has been tampered with).

It can be seen from the above this way, the recipient uses the sender all four keys, coupled with the use of the message digest, such that all three conditions previously proposed securely delivered all satisfied. It is not this way is best? No, because we have already said, asymmetric encryption is a very time-consuming operation, so this program is very inefficient. In fact, we can solve the problem symmetric encryption keys pass through it in, if you have forgotten can turn in front of another look, that is to say, we can use advanced implementations described herein to symmetric encryption cipher key delivery, for the following actual data transfer is accomplished using a symmetric encryption, because this time is safe.

1.4, certificate mechanism

A related concept is the digital signature of the certificate mechanism, the certificate is used to do what? In the above various modes, we have been using the assumption that the recipient or sender held by the other party's public key is always right (indeed other published). In fact when the public unless the other hands to us, or if no measures are taken, the two sides passing the public key in the network, as there is likely to be tampered with. So how do we solve this problem? Then you need a certificate mechanism: can introduce an impartial third party, when someone who wants to publish a public key, it will own identity information and public key submitted to the third party, a third party confirm their identity, if no problem, it is packaged into information and public key certificate (certificate) . And this impartial third party, is often said that the Certificate Authority (Certificate Authority) . When we need to obtain the public key, just need to get their credentials, and then extracts the public key on it.

2, .NET support in encryption and decryption

2.1, symmetric encryption and decryption

We believe that through the front pages of narrative, we have to understand the encryption and decryption, digital signatures basic principles, let's look at how .NET is to support encryption and decryption. As we have conducted the above classification, two .NET class also provides for encryption and decryption, a set of symmetric encryption, asymmetric encryption a group, as shown below:

 

According to the above class name can also be divided into two groups, one suffix "CryptoServiceProvider" is the class for the underlying Windows API wrapper class, a group suffix "Managed", is written in .NET completely new. Now suppose we TripleDES as an algorithm, the encryption process is as follows:

TripleDESCryptoServiceProvider first create an instance, the instance name such as call provider.

Specify the key and IV on the provider, that is, its Key property and IV property. Here briefly explain IV (initialization vector), if a string (or data) before encryption part is a lot of repetition of such ABCABCABC, then after encryption even though the string is garbled, but also duplicate the relevant part. To solve this problem, on the introduction of IV, when to use it later, even after repeated encryption also been disrupted. Can optionally specify values ​​for a specific algorithm, the key and IV, but the length is fixed, the key is typically 196 or 128, 64-bit IV. Key and IV are byte [] type, therefore, if using the Encoding class to convert a string to byte [], then the encoding mode is important, because variable length coding is UTF8, so for Chinese and English, require special attention byte [] of length problems.

If encrypted, the call provider CreateEncryptor () method to create a type of encryption ICryptoTransform object; if decryption, call the CreateDecryptor () method on the provider, is also to create a type of decryption ICryptoTransform object. ICryptoTransform defines the encryption conversion operation, .NET will call the interface at the bottom.

Because the stream and byte [] is independent of the data type, a data structure may be stored in any form of data transmission, and is different only byte [] is a static concept and the flow is a dynamic concept. Thus, using the .NET way to encrypt and decrypt the stream, we can think of two streams, a stream of plain text, containing data before encryption; is a ciphertext encrypted data stream, comprising. Then there must be a mediator plaintext into ciphertext stream flow; ciphertext or plaintext stream into a stream. Mediator to perform this operation in .NET is a flow type, called CryptoStream. It follows constructor, a total of three parameters:

public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)

When the encryption, stream cipher text stream (note that this case does not yet contain the ciphertext data stream, only an empty stream); of the ICryptoTransform scrambler is created in step 3, comprising the encryption algorithm; CryptoStreamMode enumerated as Write, means writes a plaintext stream flowing CryptoStream ciphertext stream. Finally, the encrypted data is obtained from the ciphertext stream.

When the decryption, Stream (data stream comprising ciphertext case) ciphertext stream; descrambler of the ICryptoTransform is created in step 3, comprising the decryption algorithm; CryptoStreamMode enumerated as Read, meaning that data is ciphertext stream reading out the byte [] array, then a further byte [] stream is converted to plaintext, the plaintext string.

Visible, always accept the CryptoStream ciphertext stream, and to decide whether to write plaintext stream to the stream cipher text (encryption), or the ciphertext stream into a plaintext stream (decryption) based on the value CryptoStreamMode enumeration. Here is a Helper class encryption decryption I wrote:

// 对称加密帮助类
public class CryptoHelper {

    // 对称加密算法提供器
    private ICryptoTransform encryptor;     // 加密器对象
    private ICryptoTransform decryptor;     // 解密器对象
    private const int BufferSize = 1024;

    public CryptoHelper(string algorithmName, string key) {
        SymmetricAlgorithm provider = SymmetricAlgorithm.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) { }

    // 加密算法
    public string Encrypt(string clearText) {
        // 创建明文流
        byte[] clearBuffer = Encoding.UTF8.GetBytes(clearText);
        MemoryStream clearStream = new MemoryStream(clearBuffer);

        // 创建空的密文流
        MemoryStream encryptedStream = new MemoryStream();

        CryptoStream cryptoStream =
            new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write);

        // 将明文流写入到buffer中
        // 将buffer中的数据写入到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();

        // 获取加密后的文本
        buffer = encryptedStream.ToArray();
        string encryptedText = Convert.ToBase64String(buffer);
        return encryptedText;
    }

    // 解密算法
    public string Decrypt(string encryptedText) {
        byte[] encryptedBuffer = Convert.FromBase64String(encryptedText);
        Stream encryptedStream = new MemoryStream(encryptedBuffer);

        MemoryStream clearStream = new MemoryStream();
        CryptoStream 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 carry out a simple test of the above categories:

static void Main(string[] args) {
    string key = "ABCDEFGHIJKLMNOP";
    string clearText = "欢迎访问www.tracefact.net";

    CryptoHelper helper = new CryptoHelper(key);
    
    string encryptedText = helper.Encrypt(clearText);
    Console.WriteLine(encryptedText);

    clearText = CryptoHelper.Decrypt(encryptedText, key);
    Console.WriteLine(clearText);
}

You should see the following output:

to sum up

First of all apologize to you, I did not write .NET asymmetrical encryption part, because I rarely used, so I am not very familiar with this part, but the principle should now be very clear, I want to wait until the time of need go to learn how to use them. By that time, I will also update this article once again. Through this article, I believe we have a preliminary understanding of the concept of these security encryption, decryption, digital signature, but also learn how to symmetric encryption in .NET.

 

Published 37 original articles · won praise 3 · Views 6311

Guess you like

Origin blog.csdn.net/huan13479195089/article/details/104832058