. Net encryption and decryption component tool class system Security. Cryptography. Algorith

Yes Before the emergence of the. NET Framework, if we need encryption, we only have a variety of lower level technologies to choose from, such as Microsoft Crypto API, Crypto + +, Openssl, etc., and its usage is quite complex. And in NET Framework, these complex contents (the original independent API and SDK) have been encapsulated and merged in one NET Framework class, which is very beneficial for program developers. It adapts the CryptoAPI into NET system Security. Cryptography namespace to include these encryption and signature related classes. Using these classes, we can easily use a variety of widely used algorithms, including RSA, DSA, Rijndael,** SHA and other Hash algorithms * *., The password service gets rid of the mystery of the SDK platform and becomes a simple one NET namespace.

System.Security.Cryptography.Algorith

Encryption algorithms are mainly divided into symmetric encryption algorithm, asymmetric encryption algorithm and hash algorithm (hash algorithm)

1. Symmetric key cryptography algorithm:

The encryption key and decryption key used in symmetric key cryptography algorithm are usually the same. Even if they are different, it can be easily deduced from any one of them to the other. In this algorithm, the confidentiality of the key is the top priority in this kind of application! The encryption and decryption keys used by both parties shall be kept secret. Due to the fast computing speed, symmetric encryption algorithm is widely used in the encryption process of a large number of data, such as files.
Symmetric encryption should pay attention to the block encryption mode (this is not unique to symmetry, and there is also the concept of mode in asymmetry)!
The commonly used encryption standards for digital signature using block cipher algorithm include DES, Tripl DES, RC2, RC4, CAST, etc.

2. Asymmetric encryption algorithm
Asymmetric key cryptography algorithm, also known as public key encryption algorithm, means that the encryption and decryption keys are different. Two keys are used: public key and private key. One for data encryption and one for data decryption! That is, if the data is encrypted with a public key, it can be decrypted only with the corresponding private key; If the data is encrypted with a private key, only the corresponding public key can be used to decrypt. The security of encryption is more secure than that of symmetry, but security is not absolute! The main application scenario of this algorithm is digital signature! Like RSA/DSA!
The common encryption standards for digital signature using public key cryptography algorithm are RSA, DSA and so on.

3. Encrypted hash algorithm (hash algorithm)
Hash algorithm is also called hash algorithm or digital digest. The hash algorithm converts arbitrary length data into a fixed length character sequence. Simple point is a kind of transformation, so that the transformed data represents the "label" of the data before transformation with a certain small probability. This label is hash, and transformation is hash algorithm. Often these algorithms are open and irreversible! Because the algorithm is public, in order to prevent everyone from hashing the source data, a KEY modified hash algorithm (HMAC algorithm) appears. The hash result is always one-dimensional. The hash results of any two sequences are different. The hash result is also called Finger Print. It has a fixed length, and the same plaintext digest must be consistent. In this way, the digest can become a "fingerprint" to verify whether the plaintext is "real".
Hash is mainly used to verify the validity of data. For example, BT uses SHA1 to verify whether the received data block is valid. The login of Email server has an authentication mode named HMACMD5!

characteristic:

  • The algorithm is public, and the hashing algorithm is public, that is, anyone can input hashing through the algorithm.
  • Information fingerprint, hash the same input information, and the results are consistent (this is also the origin of information fingerprint).
  • Irreversible (an output that has been hashed cannot be calculated to restore the original input). tag: but now there are also online big data to collect existing hashes for inventory storage. You can get the original input through database search.
  • Fixed length: hash the input information of different lengths, and the output is always fixed length (128 binary bits, 32 hexadecimal characters).

effect:

  • Confidentiality of user sensitive information (such as user password)
    tag: hide some user privacy information that is inconvenient to be displayed in plaintext through hashing, so that it will not lead to privacy disclosure after being stolen.
  • Search Engines
    tag: in the search engine, the search engine will guess words, that is, take the keywords in the search words for hash matching. If the matching results are consistent, the corresponding search results will be displayed.
  • Copyright protection
    tag: hash the genuine file as the genuine identification. When a user uploads a file, it is detected that the hash value of the file matches the hash in the library. If it is inconsistent, it is an infringement.
  • digital signature
    tag: This is used quite frequently in the payment field. Because the network data is usually not small, RSA encryption is directly performed on the data, which is quite a performance eating behavior. Usually, we hash the data to obtain fixed output data, and then encrypt it. This part of the encrypted hash data is the digital signature of the data. Usually, we match the signature information to the hash of the original data to prevent the data from being tampered with.

The common encryption standards for hash algorithm digital signature include SHA-1, MD5, etc.

usage method:

1.Nuget references system Security. Cryptography. Algorith

 

2. Create a new tool class Securityhelper

 public class SecurityHelper
 {
        #region md5 encryption

        /// <summary>
        ///MD5 16 bit encryption, irreversible
        /// </summary>
        /// <param name="password"></param> 
        public static string MD5Encrypt16Bit(string password)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string str = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(password)), 4, 8);
            str = str.Replace("-", "");
            return str;
        }

        /// <summary>
        ///MD5 32-bit encryption, irreversible
        /// </summary>
        /// <param name="password"></param> 
        public static string MD5Encrypt32Bit(string password)
        {
            string pwd = "";
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] str = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
            for (int i = 0; i < str.Length; i++) // By using a loop, an array of byte types is converted to a string that is formatted with regular characters
                pwd = pwd + str[i].ToString("X"); // The resulting string is in hexadecimal type format. The characters after the format are lowercase letters. If uppercase (X) is used, the characters after the format are uppercase characters 
            return pwd;
        }

        /// <summary>
        ///MD5 64 bit encryption, irreversible
        /// </summary>
        /// <param name="password"></param> 
        public static string MD5Encrypt64Bit(string password)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] str = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
            return Convert.ToBase64String(str);
        }

        #endregion

        #region

        /// <summary>
        /// SHA-1
        /// </summary>
        /// <param name="str"></param> 
        public static string SHA_1(string str)
        {
            System.Security.Cryptography.SHA1CryptoServiceProvider SHA1CSP =
                new System.Security.Cryptography.SHA1CryptoServiceProvider();
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] bytHash = SHA1CSP.ComputeHash(bytValue);
            SHA1CSP.Clear();
            string hashstr = "", tempstr = "";
            for (int counter = 0; counter < bytHash.Length; counter++)
            {
                long i = bytHash[counter] / 16;
                if (i > 9)
                    tempstr = ((char)(i - 10 + 0x41)).ToString();
                else
                    tempstr = ((char)(i + 0x30)).ToString();
                i = bytHash[counter] % 16;
                if (i > 9)
                    tempstr += ((char)(i - 10 + 0x41)).ToString();
                else
                    tempstr += ((char)(i + 0x30)).ToString();
                hashstr += tempstr;
            }

            return hashstr;
        }

        /// <summary>
        /// SHA-256
        /// </summary>
        /// <param name="str"></param> 
        public static string SHA_256(string str)
        {
            System.Security.Cryptography.SHA256CryptoServiceProvider SHA256CSP =
                new System.Security.Cryptography.SHA256CryptoServiceProvider();
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] bytHash = SHA256CSP.ComputeHash(bytValue);
            SHA256CSP.Clear();
            string hashstr = "", tempstr = "";
            for (int counter = 0; counter < bytHash.Length; counter++)
            {
                long i = bytHash[counter] / 16;
                if (i > 9)
                    tempstr = ((char)(i - 10 + 0x41)).ToString();
                else
                    tempstr = ((char)(i + 0x30)).ToString();
                i = bytHash[counter] % 16;
                if (i > 9)
                    tempstr += ((char)(i - 10 + 0x41)).ToString();
                else
                    tempstr += ((char)(i + 0x30)).ToString();
                hashstr += tempstr;
            }

            return hashstr;
        }

        /// <summary>
        /// SHA-384
        /// </summary>
        /// <param name="str"></param> 
        public static string SHA_384(string str)
        {
            System.Security.Cryptography.SHA384CryptoServiceProvider SHA384CSP =
                new System.Security.Cryptography.SHA384CryptoServiceProvider();
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] bytHash = SHA384CSP.ComputeHash(bytValue);
            SHA384CSP.Clear();
            string hashstr = "", tempstr = "";
            for (int counter = 0; counter < bytHash.Length; counter++)
            {
                long i = bytHash[counter] / 16;
                if (i > 9)
                    tempstr = ((char)(i - 10 + 0x41)).ToString();
                else
                    tempstr = ((char)(i + 0x30)).ToString();
                i = bytHash[counter] % 16;
                if (i > 9)
                    tempstr += ((char)(i - 10 + 0x41)).ToString();
                else
                    tempstr += ((char)(i + 0x30)).ToString();
                hashstr += tempstr;
            }

            return hashstr;
        }

        /// <summary>
        /// SHA-512
        /// </summary>
        /// <param name="str"></param> 
        public static string SHA_512(string str)
        {
            System.Security.Cryptography.SHA512CryptoServiceProvider SHA512CSP =
                new System.Security.Cryptography.SHA512CryptoServiceProvider();
            byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] bytHash = SHA512CSP.ComputeHash(bytValue);
            SHA512CSP.Clear();
            string hashstr = "", tempstr = "";
            for (int counter = 0; counter < bytHash.Length; counter++)
            {
                long i = bytHash[counter] / 16;
                if (i > 9)
                    tempstr = ((char)(i - 10 + 0x41)).ToString();
                else
                    tempstr = ((char)(i + 0x30)).ToString();
                i = bytHash[counter] % 16;
                if (i > 9)
                    tempstr += ((char)(i - 10 + 0x41)).ToString();
                else
                    tempstr += ((char)(i + 0x30)).ToString();
                hashstr += tempstr;
            }

            return hashstr;
        }

        #endregion
 }

3. Calling code:

class Program
{
        static void Main(string[] args)
        {
            var context = "123456789";
            var aa=DBB.Authorize.New.Common.SecurityHelper.MD5Encrypt32Bit(context);
            Console.WriteLine(aa);
            aa =DBB.Authorize.New.Common.SecurityHelper.MD5Encrypt64Bit(context);
            Console.WriteLine(aa);
            aa = DBB.Authorize.New.Common.SecurityHelper.SHA_1(context);
            Console.WriteLine(aa);
            Console.ReadLine();
        }
}

4. Output log:

Reference link: C# namespace system. In. net Security. Cryptography_ Tianfu'er's blog - CSDN blog_ system.security.cryptography

Official introduction link

System.Security.Cryptography namespace | Microsoft Docs

Keywords: C# Algorithm .NET Encryption microsoft

Added by jdesilva on Thu, 06 Jan 2022 01:20:05 +0200