DotNet encryption-symmetric encryption and dotnet encryption --

Source: Internet
Author: User
Tags dotnet net hash pkcs7

DotNet encryption-symmetric encryption and dotnet encryption --

Just one day before the Chinese New Year's Eve, it's close to you to go home. Some people are excited, because they will have to go through the annual installation drama in a few days, and all the parties, including relatives, friends, and students, will show off, therefore, I have to pay a year-end bonus to describe a stable year. Here I think of a question: "The Technology and importance of installation force ".

They are all old drivers. Don't talk nonsense. They all come in and ask the door behind them to close. Let's proceed.

The previous article mainly introduced.. NET hash encryption. The hash algorithm is mainly used for signature and other operations. In our project, if there are no special requirements for encryption, symmetric encryption is generally used, this encryption method is simpler than other encryption methods, but it is more efficient, so we will introduce it today.. NET.

1. DotNet symmetric encryption Overview:

Symmetric encryption uses a single-key encryption method, which means that encryption and decryption both use the same key. According to the definition of cryptography, the symmetric encryption system consists of five components: plaintext space, ciphertext space, key space, encryption space, and decryption algorithm. Next we will use one to represent it:


Algorithm name

Algorithm Description

DES encryption algorithmThe block encryption method is used. The 56-bit key is used to encrypt the 64-bit plaintext, And the 64-bit ciphertext is finally generated.3DES Encryption Algorithm168-bit key, triple encryption, slow speedTripleDES Encryption AlgorithmUse two keys for three data encryption/decryption operationsRC2 Encryption AlgorithmUse a variable key length to encrypt the plaintext in 64-bit packets.RC4 Encryption AlgorithmA byte stream-oriented encryption algorithm with variable key length is used, which is based on random replacement.RC5 encryption algorithmA grouping encryption algorithm with variable group length, key length, and number of encryption iterations is used. (Including key extension, encryption algorithm, and decryption algorithm)RC6 Encryption AlgorithmRC6 inherits the concept of RC5 cyclic shift. RC6 is the input plaintext and expanded from the original two zones to four blocks.Rijndael encryption algorithmThe data block and key length can be variable using the repeated encryption algorithm. The data block and key length are independent of each other.2. DotNet core object parsing of symmetric encryption:

The hierarchical structure of symmetric algorithms in. NET is as follows:

Public virtual byte [] IV {get {if (this. IVValue = null) this. generateIV (); return (byte []) this. IVValue. clone ();} set {if (value = null) throw new ArgumentNullException ("value"); if (value. length! = This. BlockSizeValue/8) throw new CryptographicException (Environment. GetResourceString ("Cryptography_InvalidIVSize"); this. IVValue = (byte []) value. Clone ();}}

This attribute represents the Key in the form of a byte array. It has the get and set attributes, indicating that this attribute is readable and writable. This attribute is a virtual attribute and can be rewritten in a subclass. The Key attribute is used to obtain or set the Key of the symmetric algorithm. The Key can be used for encryption or decryption.

(2). LegalBlockSizes attribute: obtains the block size supported by symmetric algorithms (in BITs ).

 public virtual KeySizes[] LegalBlockSizes
    {
      get
      {
        return (KeySizes[]) this.LegalBlockSizesValue.Clone();
      }
    }

This attribute is a virtual attribute that can be rewritten in the subclass. It is a read-only attribute.

(3). Create () method: Create a specified encryption object used to execute symmetric algorithms.

public static SymmetricAlgorithm Create(string algName)
    {
      return (SymmetricAlgorithm) CryptoConfig.CreateFromName(algName);
    }

This method is CryptoConfig. the CreateFromName () method is described in the previous article. We will not introduce it here. Create () receives a string parameter of the wide ricalgorithm type and specifies the System. security. cryptography. returns the ricalgorithm string.

(4). Mode attribute: obtains or sets the operation Mode of symmetric algorithms.

 public virtual CipherMode Mode
    {
      get
      {
        return this.ModeValue;
      }
      set
      {
        if (value < CipherMode.CBC || CipherMode.CFB < value)
          throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidCipherMode"));
        this.ModeValue = value;
      }
    }

This property is a virtual property. It obtains and sets the password code and pulls the prepared data. The Code shows that this property contains an enumeration type CipherMode. Let's take a look at this enumeration type:

CipherMode Enumeration type: Specifies the block encryption mode used for encryption.

   [ComVisible(true)]
    public enum CipherMode
    {
        CBC = 1,
        ECB = 2,
        OFB = 3,
        CFB = 4,
        CTS = 5
    }

CBC (Cryptographic block chain): This mode introduces class feedback; ECB (Electronic cipher book): This mode encrypts each block separately; OFB (output feedback ): in this mode, a small amount of incremental plain text is processed into the Password text instead of the entire block. In CFB (password feedback), this mode processes a small amount of incremental plain text into the Password text, instead of processing the entire block at a time; CTS (Password text stolen): This mode processes plain text of any length and generates Password text that matches the length of the plain text.

(5). Padding attribute: gets or sets the fill mode used in symmetric algorithms.

public virtual PaddingMode Padding
    {
      get
      {
        return this.PaddingValue;
      }
      set
      {
        if (value < PaddingMode.None || PaddingMode.ISO10126 < value)
          throw new CryptographicException(Environment.GetResourceString("Cryptography_InvalidPaddingMode"));
        this.PaddingValue = value;
      }
    }

This attribute is the fill mode used in symmetric algorithms. The default value is PKCS7. This attribute is readable and writable, and contains part of the data. This attribute indicates an enumeration type of PaddingMode.

PaddingMode enumeration: Specify the fill type to be applied when the message data block is short, which is more than the total number of bytes required for encryption.

  [ComVisible(true)]
    public enum PaddingMode
    {
        None = 1,
        PKCS7 = 2,
        Zeros = 3,
        ANSIX923 = 4,
        ISO10126 = 5
    }

This enumeration type has five members, None = 1: not filled; PKCS7 = 2: PKCS #7 the filling string is composed of byte sequences, and each byte is equal to the total number of added bytes; zeros = 3: The filling string consists of zero bytes; ANSIX923 = 4: ansi x 923: The filling string consists of a byte sequence with zero length before filling; ISO10126 = 5: the ISO10126 filling string consists of random data before the length.

Ii. ICryptoTransform:

ICryptoTransform defines basic encryption and conversion operations. Instances of this interface can convert plain text into encrypted text, or convert encrypted text into plain text. Each ICryptoTransform is unidirectional, it can only be used for the purpose of its creation. The attributes and methods of this interface are as follows:

/// <summary>
     /// Get the input block size.
     /// </ summary>
     int InputBlockSize {get;}
     /// <summary>
     /// Get the output block size.
     /// </ summary>
     int OutputBlockSize {get;}
     /// <summary>
     /// Get a value indicating whether multiple blocks can be converted.
     /// </ summary>
     bool CanTransformMultipleBlocks {get;}
     /// <summary>
     /// Get a value indicating whether the current transformation can be reused.
     /// </ summary>
     bool CanReuseTransform {get;}
     /// <summary>
     /// Convert the specified area of the input byte array and copy the resulting conversion to the specified area of the output byte array.
     /// </ summary>
     int TransformBlock (byte [] inputBuffer, int inputOffset, int inputCount, byte [] outputBuffer, int outputOffset);
     /// <summary>
     /// Convert the specified area of the specified byte array.
     /// </ summary>
  byte [] TransformFinalBlock (byte [] inputBuffer, int inputOffset, int inputCount);

The ICryptoTransform interface instance cannot be used by itself.. NET provides the CryptoStream class that defines linking data streams to encrypted conversion streams. To create a CryptoStream instance, a real stream, ICryptoTransform, and CryptoStreamMode enumeration value is required.

Iii. DotNet symmetric encryption instance: 1. DES algorithm encryption instance:
/// <summary>
        /// encrypted data
        /// </ summary>
        /// <param name = "text"> </ param>
        /// <param name = "sKey"> </ param>
        /// <returns> </ returns>
        public static string Encrypt (string text, string sKey)
        {
            if (string.IsNullOrEmpty (text))
            {
                throw new ArgumentNullException (text);
            }
            if (string.IsNullOrEmpty (sKey))
            {
                throw new ArgumentNullException (sKey);
            }
            MemoryStream ms = null;
            DESCryptoServiceProvider des = null;
            try
            {
                des = new DESCryptoServiceProvider ();
                var inputByteArray = Encoding.Default.GetBytes (text);
                var bKey = Encoding.ASCII.GetBytes (Md5Hash (sKey) .Substring (0, 8));
                des.Key = bKey;
                des.IV = bKey;
                ms = new MemoryStream ();
                var cs = new CryptoStream (ms, des.CreateEncryptor (), CryptoStreamMode.Write);
                cs.Write (inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock ();
                var ret = new StringBuilder ();
                foreach (byte b in ms.ToArray ())
                {
                    ret.AppendFormat ("{0: X2}", b);
                }
                return ret.ToString ();
            }
            catch (NotSupportedException nsex)
            {
                throw nsex;
            }
            catch (ArgumentNullException arnex)
            {
                throw arnex;
            }
            catch (EncoderFallbackException efex)
            {
                throw efex;
            }
            catch (ArgumentException arex)
            {
                throw arex;
            }
            catch (CryptographicException crex)
            {
                throw crex;
            }
            finally
            {
                if (ms! = null)
                {
                    ms.Close ();
                }
                if (des! = null)
                {
                    des.Clear ();
                }
            }
        }
2. DES algorithm decryption instance:
/// <summary>
        /// decrypt the data
        /// </ summary>
        /// <param name = "text"> </ param>
        /// <param name = "sKey"> </ param>
        /// <returns> </ returns>
        public static string Decrypt (string text, string sKey)
        {
            if (string.IsNullOrEmpty (text))
            {
                throw new ArgumentNullException (text);
            }
            if (string.IsNullOrEmpty (sKey))
            {
                throw new ArgumentNullException (sKey);
            }
            MemoryStream ms = null;
            DESCryptoServiceProvider des = null;
            try
            {
                des = new DESCryptoServiceProvider ();
                var len = text.Length / 2;
                byte [] inputByteArray = new byte [len];
                int x;
                for (x = 0; x <len; x ++)
                {
                    var i = Convert.ToInt32 (text.Substring (x * 2, 2), 16);
                    inputByteArray [x] = (byte) i;
                }
                var bKey = Encoding.ASCII.GetBytes (Md5Hash (sKey) .Substring (0, 8));
                des.Key = bKey;
                des.IV = bKey;
                ms = new MemoryStream ();
                CryptoStream cs = new CryptoStream (ms, des.CreateDecryptor (), CryptoStreamMode.Write);
                cs.Write (inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock ();
                return Encoding.Default.GetString (ms.ToArray ());
            }
            catch (NotSupportedException nsex)
            {
                throw nsex;
            }
            catch (ArgumentNullException arnex)
            {
                throw arnex;
            }
            catch (EncoderFallbackException efex)
            {
                throw efex;
            }
            catch (ArgumentException arex)
            {
                throw arex;
            }
            catch (CryptographicException crex)
            {
                throw crex;
            }
            finally
            {
                if (ms! = null)
                {
                    ms.Close ();
                }
                if (des! = null)
                {
                    des.Clear ();
                }
            }
        } 
Iv. Summary:

This blog post mainly explains. NET's symmetric encryption method, its principles, source code analysis, and corresponding instances to help us understand encryption. If you have any errors or deficiencies, Please comment and correct them.


Related Article

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.