C-encryption and decryption (DES\RSA) learning notes

This note is excerpted from: https://www.cnblogs.com/skylaugh/archive/2011/07/12/2103572.html Record the learning process for future reference.

Data encryption technology is the most basic security technology in the network, mainly through the data encryption of the information transmitted in the network to ensure its security, which is an active security defense strategy, with a very small cost

Can provide considerable security protection for information.

I. Basic concepts of encryption

"Encryption" is a technology that limits access to data transmitted over the network. The encoded data produced by the original data (also known as plaintext) encrypted by the encryption device (hardware or software) and the key

It's called ciphertext. The process of restoring the ciphertext to the original plaintext is called decryption, which is the reverse process of encryption, but the decryptor must use the same type of encryption device and key to decrypt the ciphertext.

The basic functions of encryption include:

1) prevent uninvited visitors from viewing confidential data files.

2) prevent confidential data from being disclosed or tampered.

3) prevent privileged users (such as system administrators) from viewing private data files.

4) the intruder can not easily find a system file.

Data encryption is an important mechanism to ensure the security of computer network. Although it has not been popularized in the network at present due to the complexity of cost, technology and management, data encryption is indeed the realization of distribution

One of the important means of data security in the network environment.

Data encryption can be implemented in the network OSI seven layer protocol (OSI is the abbreviation of open system interconnection, which means open system interconnection). The international standards organization (ISO) has developed the OSI model. this

Each model divides the work of network communication into seven layers: physical layer, data link layer, network layer, transport layer, session layer, presentation layer and application layer. )So from the logic of encryption technology application

There are three ways of editing location:

1) link encryption: generally, the encryption below the network layer is called link encryption, which is mainly used to protect the data transmitted between the communication nodes. The encryption and decryption are implemented by the cryptographic equipment placed on the line. According to the same

Synchronous communication encryption includes byte synchronous communication encryption and bit synchronous communication encryption.

2) node encryption: it is an improvement of link encryption. In the protocol transmission layer, encryption is mainly used to protect the transmission data between the source node and the target node. Similar to the link encryption, it is only encrypted

The method is combined with the encryption module attached to the node, which overcomes the disadvantage that the link encryption is easy to be accessed illegally at the node.

3) end to end encryption: the encryption above the network layer is called end-to-end encryption, which is oriented to the main body of the network layer. Encrypting the data information in the application layer is easy to realize with software, and the cost is low, but the key management problem

Difficult, mainly suitable for large-scale network system information transmission between multiple senders and receivers.

II. Application of data encryption

1) media encryption: DRM

2) file encryption: text encryption, pdf, word

3) data encryption: Data Encryption in C ×

4) hardware encryption: dongle

III. Development Trend of encryption technology

1) combination of private key encryption technology and public key encryption technology: in view of the characteristics of the two encryption systems, a compromise scheme can be adopted in practical application, that is, DES/IDEA and RSA can be used in combination

DES is the "kernel" and RSA is the "shell". For the data transmitted in the network, des or IDEA can be used for encryption, while the key used for encryption is transmitted by RSA encryption. This method not only ensures the data security but also improves the encryption

And the speed of decryption, which is also one of the new directions of the development of encryption technology.

2) search for new algorithm: jump out of the construction idea based on common iteration, and break away from the construction method based on the complexity of some mathematical problems. For example, Liu's algorithm proposed by Mr. Liu Zunquan is a public key based public key

Open key system. It uses the principle of randomness to construct the encryption and decryption transformation, and hides all its operation control in the key, and the key length is variable; it uses a certain length of segmentation to construct a large search space, from

And realize a nonlinear transformation. This encryption algorithm has the advantages of high encryption intensity, high speed and low computation cost.

3) encryption will eventually be integrated into the system and network. For example, IPV6 protocol already has built-in encryption support. In terms of hardware, Intel company is developing an encryption coprocessor, which can be integrated into microcomputer

On the motherboard.

IV. classification of encryption technology

There are four types of encryption:

1) the problem of decryption is not considered at all.

2) private key encryption technology Symmetric Key Encryption: symmetric encryption uses the same key for encryption and decryption. Generally, this encryption method is difficult to implement in application

For example, RC4, RC2, DES and AES series encryption algorithms are difficult to share the key in the same security way.

3) public key encryption technology -- Asymmetric Key Encryption: Asymmetric Key Encryption uses a group of public / private key systems, uses a key when encrypting, and uses a key when decrypting

Use another key. Public key can be widely shared and disclosed. When it is necessary to transmit data to the outside of the server by encryption, this encryption method is more convenient, such as RSA.

4) Certificate: digital certificate is a kind of asymmetric key encryption. However, an organization can use certificate to associate a group of public key and private key with its owner through digital signature.

5. DES encryption and decryption of symmetric encryption

5.1 symmetric encryption

Symmetric encryption is a more traditional way of encryption, which uses the same key for encryption and decryption. When transmitting and processing information, the sender and receiver of information must share the same key

The same as holding the password (called symmetric password). Therefore, both sides of the communication must obtain the key and keep the key secret.

The security of a single key cryptosystem depends on two factors:

First, the encryption algorithm must be strong enough. It is impossible to decrypt information only based on the ciphertext itself in practice.

Second, the security of encryption method depends on the secret of the key, not the secret of the algorithm. Therefore, we do not need to ensure the secret of the algorithm (in fact, many single key cryptosystems used in reality

But we must guarantee the secret of the key.

DES(Data Encryption Standard) and TripleDES are two implementations of symmetric encryption:

1) the basic algorithm of DES and TripleDES is the same, but TripleDES algorithm provides more key bits and higher encryption reliability.

2) the key key used by DES is 8 bytes, and the initial vector IV is also 8 bytes.

3) the key key of TripleDES is 24 bytes, and the initial vector IV is also 8 bytes.

4) both algorithms are encrypted with 8 bytes as a block, one data block as a data block, and the ciphertext encrypted with 8 bytes of plaintext is also 8 bytes. If the plaintext length is not an integer of 8 bytes

Times, add a byte with a value of 0 to make up an integer multiple of 8 bytes, so the encrypted ciphertext length must be an integer multiple of 8 bytes.

5.2 encryption and decryption process

The above figure is the encryption and decryption process of the whole DES and TripleDES algorithm. Next, take TripleDES as an example, analyze each step of encryption and decryption combined with dotnet, and give the relevant implementation code.

5.2.1 generate Key and IV

The System.Security.Cryptography.TripleDESCryptoServiceProvider class is the main class to implement TripleDES algorithm in. NET.

The TripleDESCryptoServiceProvider class has only one construction method, TripleDESCryptoServiceProvider(), which initializes some properties:

KeySize (encryption key length in bits) = 192 (24 bytes)

BlockSize = 64 (8 bytes)

FeedbackSize (the size of the data returned after encrypting the data block, in bits) = 64 (8 bytes)

The TripleDESCryptoServiceProvider constructor initializes a random set of keys and IV at the same time.

The Key of the default TripleDESCryptoServiceProvider is 24 bytes, IV is 8 bytes, and the encrypted data block is 8 bytes.

The code for generating Key and IV is simple:

TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
byte[] keyArray = tripleDES.Key;
byte[] ivArray = tripleDES.IV;

5.2.2 conversion of string plaintext to encoded byte stream

There are two possible forms of data to be encrypted: one is binary data, which is a set of byte streams. Such data can skip this step and enter the encryption step directly; the other is string number

According to, the same character in a string will generate different bytecodes with different encodings, so the conversion from string to byte stream needs to specify the encodings to be used. After decryption, convert from byte stream to character

The string must be decoded with the same encoding, otherwise, it will be scrambled.

//String to be encrypted
string plainTextString = "Here is some data to encrypt.";
//Use utf-8 Coding (other coding can also be used)
Encoding encoding = Encoding.GetEncoding("utf-8");
//Convert string plaintext to utf-8 Encoded byte stream
byte[] plainTextArray = encoding.GetBytes(plainTextString);

5.2.3 encryption operation

The raw material of encryption is plaintext byte stream. TripleDES algorithm encrypts byte stream and returns encrypted byte stream. At the same time, Key and IV used for encryption should be given.

    /// <summary>
    /// Encryption and decryption help class
    /// </summary>
    public static class CryptoHelper
    {
        /// <summary>
        /// Symmetric encryption TripleDes encryption
        /// </summary>
        /// <param name="plainTextArray">Clear text byte array</param>
        /// <param name="Key">Key</param>
        /// <param name="IV">IV</param>
        /// <returns>Return byte array</returns>
        public static byte[] TripleDesEncrypt(string plainText, byte[] Key, byte[] IV)
        {
            //Convert clear text string to clear text byte array
            Encoding encoding = Encoding.GetEncoding("utf-8");
            byte[] plainTextArray = encoding.GetBytes(plainText);

            //Build a new one. MemoryStream Object store encrypted data stream
            MemoryStream memoryStream = new MemoryStream();

            //Build a new one. CryptoStream object
            CryptoStream cryptoStream = new CryptoStream
                (
                    memoryStream,
                    new TripleDESCryptoServiceProvider().CreateEncryptor(Key, IV),
                    CryptoStreamMode.Write
                );

            //Write encrypted byte stream to memoryStream
            cryptoStream.Write(plainTextArray, 0, plainTextArray.Length);

            //Update the last state in the buffer to memoryStream´╝îAnd clear cryptoStream Cache for.
            cryptoStream.FlushFinalBlock();

            //Transfer encrypted data to byte stream
            byte[] result = memoryStream.ToArray();

            //Close two Stream
            cryptoStream.Close();
            memoryStream.Close();

            //Return result
            return result;
        }
    }

5.2.4 decryption operation

Decryption of the ciphertext byte [] generated in 5.2.3 requires the use of the same set of keys and IV used in the encryption step.

    /// <summary>
    /// Encryption and decryption help class
    /// </summary>
    public static class CryptoHelper
    {
        /// <summary>
        /// Symmetric encryption TripleDes Decrypt
        /// </summary>
        /// <param name="encryptTextArray">Encrypted byte array</param>
        /// <param name="Key">Key</param>
        /// <param name="IV">IV</param>
        /// <returns>Return string</returns>
        public static string TripleDesDecrypt(byte[] encryptTextArray, byte[] Key, byte[] IV)
        {
            //Convert encrypted string to encrypted byte array
            Encoding encoding = Encoding.GetEncoding("utf-8");

            //Build a new one. MemoryStream Object store decrypted data flow
            MemoryStream memoryStream = new MemoryStream(encryptTextArray);

            //Build a new one. CryptoStream object
            CryptoStream cryptoStream = new CryptoStream
                (
                    memoryStream,
                    new TripleDESCryptoServiceProvider().CreateDecryptor(Key, IV),
                    CryptoStreamMode.Read
                );

            //Create a new plaintext byte array for decryption (it may be longer than the plaintext before encryption)
            byte[] decryptTextArray = new byte[encryptTextArray.Length];

            //Read the decrypted data stream to
            cryptoStream.Read(decryptTextArray, 0, decryptTextArray.Length);

            //Close two Stream
            memoryStream.Close();
            cryptoStream.Close();

            return encoding.GetString(decryptTextArray);
        }
    }

It should be noted that DES encryption is based on data block, 8 bytes per data block. If the length of the plaintext byte [] to be encrypted is not an integer multiple of 8 bytes, the algorithm first uses the byte whose value is "0" to supplement

Enough 8 bytes, and then encryption, so the encrypted ciphertext length must be an integer multiple of 8. If the bytes of 0 value are added after decryption of such ciphertext, the bytes of 0 value still exist after decryption.

5.2.5 example

    class Program
    {
        static void Main(string[] args)
        {
            #region Symmetric encryption TripleDes encryption and decryption 
            //Plaintext data
            string plainText = "Life is like a play, all depends on acting.";

            //generate Key and IV
            TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
            byte[] keyArray = tripleDES.Key;
            byte[] ivArray = tripleDES.IV;

            //encryption
            byte[] encryptTextArray = CryptoHelper.TripleDesEncrypt(plainText, keyArray, ivArray);

            //Decrypt
            string decryptText = CryptoHelper.TripleDesDecrypt(encryptTextArray, keyArray, ivArray);

            //output
            Console.WriteLine($"Clear text data:{plainText}");
            Console.WriteLine($"Data after decryption:{decryptText}");
            Console.Read();
            #endregion
        }
    }

The operation results are as follows:

Vi. explanation of RSA encryption and decryption of asymmetric encryption

RSA public key encryption algorithm was developed by Ron Rivest, Adi Shamirh and Len Adleman in 1977. RSA was named after three of them. RSA is the eye.

The former most influential public key encryption algorithm, which can resist all known password attacks so far, has been recommended as the public key data encryption standard by ISO; RSA algorithm is based on a very simple number theory fact:

It's very easy to multiply two prime numbers, but it's very difficult to factorize the product, so we can make the product public as encryption key; RSA algorithm is the first one that can be used for encryption and digital signature at the same time

Name algorithm, also easy to understand and operate.

RSA algorithm is the most widely studied public key algorithm. It has been nearly 20 years since it was proposed. It has been tested by various attacks and gradually accepted by people. It is generally considered as the best public key scheme at present

One. The security of RSA depends on factorization of large numbers, but it has not been proved theoretically that the difficulty of deciphering RSA is equivalent to that of factorization of large numbers, that is to say, the major defect of RSA is that it cannot grasp its security in theory

What can be done, and most people in cryptography tend to factor decomposition is not NPC problem.

The disadvantages of RSA are as follows:

1) it is very difficult to generate the secret key, which is limited by the prime number generation technology, so it is difficult to achieve one secret at a time.

2) the packet length is too large. In order to ensure security, n must be at least 600 bits, which leads to high computational cost, especially slow speed (several orders of magnitude slower than symmetric cipher algorithm), and with the large number decomposition technology

With the development of, this length is still increasing, which is not conducive to the standardization of data format. At present, the SET(Secure Electronic Transaction) protocol requires CA to use 2048bits long key, and other entities use

A key of 1024 bits.

3) the length of RSA key increases rapidly with the increase of security level.

The following table lists the key lengths for the same security level:

Confidentiality level

Symmetric key length (bit)

RSA key length (bit)

ECC key length (bit)

Secrecy years

80

80

1024

160

2010

112

112

2048

224

2030

128

128

3072

256

2040

192

192

7680

384

2080

256

256

15360

512

2120

RSA algorithm is a kind of asymmetric cipher algorithm. The so-called asymmetric means that the algorithm needs a pair of keys. If one of them is used for encryption, it needs another to decrypt.

RSA algorithm involves three parameters n, e1 and e2:

1) n is the product of two prime numbers p and q. the number of bits occupied by the binary representation of n is the so-called key length.

2) e1 and e2 are a pair of related values. E1 can be taken at will, but E1 and (p-1)*(q-1) are required to be mutually prime, and then e2 is selected, requiring (e2*e1)mod((p-1)*(q-1))=1.

3) (n and e1), (n and e2) are key pairs.

The algorithm of RSA encryption and decryption is the same. If A is plaintext and B is ciphertext, then A=B^e1 mod n; B=A^e2 mod n;

e1 and e2 can be used interchangeably, that is, A=B^e2 mod n; B=A^e1 mod n;

6.1 generate a pair of public keys and keys

    /// <summary>
    /// Encryption and decryption help class
    /// </summary>
    public static class CryptoHelper
    {
        /// <summary>
        /// Asymmetric encryption RSA Generate public key
        /// </summary>
        public static void RSACreateKey()
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            //Public key
            using (StreamWriter writer = new StreamWriter(@"..\..\PublicKey.xml"))
            {
                writer.WriteLine(rsa.ToXmlString(false));
            }
            //Key (please keep secret)
            using (StreamWriter writer = new StreamWriter(@"..\..\PrivateKey.xml"))
            {
                writer.WriteLine(rsa.ToXmlString(true));
            }
        }
    }

6.2 encryption operation

    /// <summary>
    /// Encryption and decryption help class
    /// </summary>
    public static class CryptoHelper
    {
        /// <summary>
        /// Asymmetric encryption RSA encryption
        /// </summary>
        /// <param name="publickey">Public key</param>
        /// <param name="plainText">Clear text string</param>
        /// <returns>Encrypted string</returns>
        public static string RSAEncrypt(string publickey, string plainText)
        {
            StreamReader reader = new StreamReader(@"..\..\PublicKey.xml", Encoding.UTF8);
            publickey = reader.ReadToEnd();
            reader.Close();

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(publickey);
            byte[] cipherBytes = rsa.Encrypt(Encoding.UTF8.GetBytes(plainText), false);

            return Convert.ToBase64String(cipherBytes);
        }
    }

6.3 decryption operation

    /// <summary>
    /// Encryption and decryption help class
    /// </summary>
    public static class CryptoHelper
    {
        /// <summary>
        /// Asymmetric encryption RSA Decrypt
        /// </summary>
        /// <param name="privatekey">secret key</param>
        /// <param name="encryptText">Encrypted string</param>
        /// <returns>Decrypt string</returns>
        public static string RSADecrypt(string privatekey, string encryptText)
        {
            StreamReader reader = new StreamReader(@"..\..\PrivateKey.xml", Encoding.UTF8);
            privatekey = reader.ReadToEnd();
            reader.Close();

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(privatekey);
            byte[] cipherBytes = rsa.Decrypt(Convert.FromBase64String(encryptText), false);

            return Encoding.UTF8.GetString(cipherBytes);
        }
    }

6.4 example

    class Program
    {
        static void Main(string[] args)
        {
            #region Asymmetric encryption RSA encryption and decryption 
            //Plaintext data
            string plainText = "Life is like a play, all depends on acting.";

            //Generate public key and key
            CryptoHelper.RSACreateKey();

            //encryption
            string encryptText = CryptoHelper.RSAEncrypt("", plainText);

            //Decrypt
            string decryptText = CryptoHelper.RSADecrypt("", encryptText);

            Console.WriteLine($"Clear text data:{plainText}\n");
            Console.WriteLine($"Encrypted data:{encryptText}\n");
            Console.WriteLine($"Data after decryption:{decryptText}");
            Console.Read();
            #endregion
        }
    }

The operation results are as follows:

Keywords: C# encoding network xml Session

Added by EverToDesign on Sat, 04 Jan 2020 20:28:24 +0200