C # commonly used encryption algorithms: MD5, Base64, SHA1, SHA256, HmacSHA256, DES, AES, RSA

Posted by imartin on Sun, 23 Jan 2022 08:07:35 +0100

c# tutorialhttps://www.xin3721.com/eschool/CSharpxin3721/

brief introduction

This article mainly explains the C# commonly used encryption algorithms, including MD5, Base64, SHA1, SHA256, HmacSHA256, DES, AES, RSA encryption, etc. friends in need can refer to it

Class to reference

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

You also need to install bouncy castle
In the menu bar, find tools - > NuGet Package Manager - > manage NuGet packages for solutions - > Browse - > search for "BouncyCastle" - > install

Public fields defined by myself; Friends in need can define themselves

        private static CspParameters Param;

        /// <summary>
        ///SK(Secret Access Key): a key used in combination with the access key ID to encrypt and sign the request, identify the sender and prevent the request from being modified
        /// </summary>
        public static string _appSecret = ConfigurationManager.AppSettings["appSecret"].ToString();

        /// <summary>
        ///AK(Access Key ID): access key ID. A unique identifier associated with the private access key; The access key ID is used together with the private access key to encrypt and sign the request
        /// </summary>
        public static string _appKey = ConfigurationManager.AppSettings["appKey"].ToString();

        /// <summary>
        ///DES key
        /// </summary>
        private static byte[] _KEY = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };

        /// <summary>
        ///DES vector
        /// </summary>
        private static byte[] _IV = new byte[] { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 };

        /// <summary>
        ///Default public key for RSA encryption / decryption
        /// </summary>
        private static string _publicKey = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

        /// <summary>
        ///Default private key for RSA decryption / encryption
        /// </summary>
        private static string _privateKey = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent><P>/hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==</P><Q>6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==</Q><DP>ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==</DP><DQ>MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==</DQ><InverseQ>EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==</InverseQ><D>vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=</D></RSAKeyValue>";

        /// <summary>
        ///8-bit encryption key
        /// </summary>
        private static string keys = "olikjhgb";

        /// <summary>
        ///16 bit encryption key
        /// </summary>
        private static string Key = "1123uyrlouhd@_Lq";

        /// <summary>
        ///Default vector above 16 bits
        /// </summary>
        private static string vector = "*abcdefghijklmnopqrst@";

1, MD5 encryption

  • MD5 encryption is the most common encryption method. Because MD5 is irreversible, many system passwords are saved with MD5 encryption.
  • Although MD5 encryption is irreversible, we can encrypt the plaintext again and compare the ciphertext encrypted twice
        #region MD5 encryption and decryption
        /// <summary>
        ///16 bit MD5 encryption
        /// </summary>
        ///< param name = "laws" > plaintext string to be encrypted < / param >
        /// <returns></returns>
        public static string MD5Encrypt16(string laws)
        {
            var md5 = new MD5CryptoServiceProvider();
            string cipherText = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(laws)), 4, 8);
            cipherText = cipherText.Replace("-", "");
            return cipherText;
        }

        /// <summary>
        ///32-bit MD5 encryption
        /// </summary>
        ///< param name = "laws" > plaintext string to be encrypted < / param >
        ///< returns > 32-bit MD5 encrypted ciphertext string < / returns >
        public static string MD5Encrypt32(string laws)
        {
            string plainText = laws;
            string rule = "";
            MD5 md5 = MD5.Create(); //Instantiate an md5 object
                                    // After encryption, it is an array of byte type. Pay attention to the selection of encoding UTF8/Unicode, etc
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(plainText));
            // By using a loop, an array of byte types is converted to a string that is formatted with regular characters
            for (int i = 0; i < s.Length; i++)
            {
                // 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 
                rule = rule + s[i].ToString("x2");
            }
            return rule;
        }

        /// <summary>
        ///64 bit MD5 encryption
        /// </summary>
        ///< param name = "laws" > plaintext string to be encrypted < / param >
        ///< returns > 64 bit MD5 encrypted ciphertext string < / returns >
        public static string MD5Encrypt64(string laws)
        {
            string rule = laws;
            MD5 md5 = MD5.Create(); //Instantiate an md5 object
            // After encryption, it is an array of byte type. Pay attention to the selection of encoding UTF8/Unicode, etc
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(rule));
            return Convert.ToBase64String(s);
        }

        /// <summary>
        ///MD5 encryption of string
        /// </summary>
        ///< param name = "sourcestr" > source type < / param >
        ///< returns > encrypted string < / returns >
        public static string Md5Encrypt(string sourceStr)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            //Converts the string to be encrypted into a byte array
            byte[] palindata = Encoding.Default.GetBytes(sourceStr);
            //Encryption via byte array
            byte[] encryptdata = md5.ComputeHash(palindata);
            //Convert the encrypted byte array into a string
            string returnData = Convert.ToBase64String(encryptdata);
            return returnData;
        }

        /// <summary>
        ///Md5 key encryption
        /// </summary>
        ///< param name = "ptoencrypt" > string to encrypt < / param >
        /// <returns></returns>
        public static string Md5Encrypt_Key(string pToEncrypt)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            des.Key = Encoding.ASCII.GetBytes(keys);
            des.IV = Encoding.ASCII.GetBytes(keys);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            var s = ret.ToString();
            return s;
        }

        /// <summary>
        ///Md5 decryption
        /// </summary>
        ///< param name = "ptodecrypt" > decrypt string < / param >
        /// <returns></returns>
        public static string Md5Decrypt(string pToDecrypt)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            des.Key = Encoding.ASCII.GetBytes(_appSecret);
            des.IV = Encoding.ASCII.GetBytes(_appSecret);
            MemoryStream 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());
        }

        /// <summary>
        ///MD5 stream encryption
        /// </summary>
        ///< param name = "InputStream" > input stream < / param >
        /// <returns></returns>
        public static string GenerateMD5(Stream inputStream)
        {
            using (MD5 mi = MD5.Create())
            {
                //Start encryption
                byte[] newBuffer = mi.ComputeHash(inputStream);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }
#endregion

2, Base64 encoding and decoding

  • Strictly speaking, Base64 is a kind of encoding rather than encryption. Usually, the string encoded by Base64 will be used to transmit data. However, it is precisely because the base64 encoded string is unreadable; It is also used as an encryption algorithm.
        #region Base64 encoding and decoding
        /// <summary>
        ///Base64 coding, using utf8 coding
        /// </summary>
        ///< param name = "strpath" > plaintext to be encoded < / param >
        ///< returns > Base64 encoded string < / returns >
        public static string Base64Encrypt(string strPath)
        {
            string returnData;
            Encoding encode = Encoding.UTF8;
            byte[] bytedata = encode.GetBytes(strPath);
            try
            {
                returnData = Convert.ToBase64String(bytedata, 0, bytedata.Length);
            }
            catch
            {
                returnData = strPath;
            }
            return returnData;
        }

        /// <summary>
        ///Base64 decoding, using utf8 encoding
        /// </summary>
        ///< param name = "strpath" > ciphertext to be decoded < / param >
        ///< returns > Base64 decoded plaintext string < / returns >
        public static string Base64DesEncrypt(string strPath)
        {
            string returnData;
            byte[] bpath = Convert.FromBase64String(strPath);
            try
            {
                returnData = Encoding.UTF8.GetString(bpath);
            }
            catch
            {
                returnData = strPath;
            }
            return returnData;
        }
        #endregion

3, SHA encryption and decryption

  • SHA1 encryption algorithm is similar to MD5 encryption, which is irreversible, but the algorithm is different.
        /// <summary>
        ///SHA1 encryption 
        /// </summary>
        ///< param name = "content" > need to encrypt string < / param >
        ///< param name = "encode" > specify the encryption code < / param >
        ///< param name = "upperorlower" > case format (uppercase: x2; lowercase: x2) default lowercase < / param > 
        public static string SHA1Encrypt(string content, Encoding encode, string upperOrLower = "x2")
        {
            try
            {
                var buffer = encode.GetBytes(content);//Convert to bytes array with specified encoding
                var data = SHA1.Create().ComputeHash(buffer);
                var sb = new StringBuilder();
                foreach (var t in data)
                {
                    sb.Append(t.ToString(upperOrLower));
                }

                return sb.ToString();
            }
            catch (Exception ex)
            {
                return "SHA1 Encryption error:" + ex.Message;
            }
        }

        /// <summary>
        ///SHA256 encryption
        /// </summary>
        ///< param name = "string" > string to encrypt < / param >
        ///< returns > sha256 encrypted ciphertext < / returns >
        public static string SHA256Encrypt(string strIN)
        {
            byte[] tmpByte;
            SHA256 sha256 = new SHA256Managed();
            tmpByte = sha256.ComputeHash(GetKeyByteArray(strIN));

            StringBuilder rst = new StringBuilder();
            for (int i = 0; i < tmpByte.Length; i++)
            {
                rst.Append(tmpByte[i].ToString("x2"));
            }
            sha256.Clear();
            return rst.ToString();
        }
        
        /// <summary>
        ///Gets the string byte array to be encrypted
        /// </summary>
        ///< param name = "strkey" > string to be encrypted < / param >
        ///< returns > encrypted array < / returns >
        private static byte[] GetKeyByteArray(string strKey)
        {
            UTF8Encoding Asc = new UTF8Encoding();
            int tmpStrLen = strKey.Length;
            byte[] tmpByte = new byte[tmpStrLen - 1];
            tmpByte = Asc.GetBytes(strKey);
            return tmpByte;
        }

4, HmacSHA256 Base64 encryption

        /// <summary>
        ///HmacSHA256 Base64 algorithm, the returned result is always 32 bits
        /// </summary>
        ///< param name = "message" > plaintext string to be encrypted < / param >
        ///< returns > ciphertext encrypted by hmacsha256 algorithm < / returns >
        public static string HmacSHA256(string message)
        {
            byte[] keyByte = Encoding.GetEncoding("utf-8").GetBytes(_appSecret);
            byte[] messageBytes = Encoding.GetEncoding("utf-8").GetBytes(message);
            using (var hmacsha256 = new HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return Convert.ToBase64String(hashmessage);
            }
        }

5, DES encryption and decryption

  • DES(Data Encryption Standard) is one of the most popular encryption algorithms. DES is symmetric, that is, it uses the same key to encrypt and decrypt data.
  • DES is also a packet encryption algorithm, which processes fixed length data segments each time, which is called packet.
  • DES encryption algorithm requires the key to be 8 characters, such as 12345678.
        #Region DES encryption and decryption
        /// <summary>
        ///DES encryption operation
        /// </summary>
        ///< param name = "normalxt" > plaintext string to be encrypted < / param >
        ///< returns > returns the ciphertext string encrypted by DES < / returns >
        public static string DesEncrypt(string normalTxt)
        {
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(_KEY, _IV), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(cst);
            sw.Write(normalTxt);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();

            string strRet = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
            return strRet;
        }

        /// <summary>
        ///DES decryption operation
        /// </summary>
        ///< param name = "securitytxt" > ciphertext string to be decrypted < / param >
        ///< returns > returns the plaintext string after DES decryption < / returns >
        public static string DesDecrypt(string securityTxt)//decrypt  
        {
            byte[] byEnc;
            try
            {
                securityTxt.Replace("_%_", "/");
                securityTxt.Replace("-%-", "#");
                byEnc = Convert.FromBase64String(securityTxt);
            }
            catch
            {
                return null;
            }
            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(_KEY, _IV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }
#endregion

6, AES encryption and decryption

  • AES (Advanced Encryption Standard) is the most common symmetric encryption algorithm (this encryption algorithm is used for encrypted transmission of wechat applet)
#region AES encryption and decryption
        /// <summary>
        ///AES base64 encryption algorithm; Key is 16 bits
        /// </summary>
        ///< param name = "data" > string to be encrypted < / param >
        /// <returns></returns>
        public static string RST_AesEncrypt_Base64(string Data)
        {
            if (string.IsNullOrEmpty(Data))
            {
                return null;
            }
            if (string.IsNullOrEmpty(Key))
            {
                return null;
            }
            string Vector = Key.Substring(0, 16);
            Byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
            Byte[] bKey = new Byte[32];
            Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
            Byte[] bVector = new Byte[16];
            Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
            Byte[] Cryptograph = null; // Encrypted ciphertext  
            Rijndael Aes = Rijndael.Create();
            //add 
            Aes.Mode = CipherMode.CBC;//des in other languages
            Aes.BlockSize = 128;
            Aes.Padding = PaddingMode.PKCS7;
            //add end
            try
            {
                // Open up a memory stream  
                using (MemoryStream Memory = new MemoryStream())
                {
                    // Wrap the memory stream object into an encrypted stream object  
                    using (CryptoStream Encryptor = new CryptoStream(Memory,
                     Aes.CreateEncryptor(bKey, bVector),
                     CryptoStreamMode.Write))
                    {
                        // Write plaintext data to encrypted stream  
                        Encryptor.Write(plainBytes, 0, plainBytes.Length);
                        Encryptor.FlushFinalBlock();

                        Cryptograph = Memory.ToArray();
                    }
                }
            }
            catch
            {
                Cryptograph = null;
            }
            return Convert.ToBase64String(Cryptograph);
        }

        /// <summary>
        ///AES base64 decryption algorithm; Key is 16 bits
        /// </summary>
        ///< param name = "data" > string to be decrypted < / param >
        ///< param name = "key" > key is a 16 bit key < / param >
        /// <returns></returns>
        public static string RST_AesDecrypt_Base64(string Data)
        {
            try
            {
                if (string.IsNullOrEmpty(Data))
                {
                    return null;
                }
                if (string.IsNullOrEmpty(Key))
                {
                    return null;
                }
                string Vector = Key.Substring(0, 16);
                Byte[] encryptedBytes = Convert.FromBase64String(Data);
                Byte[] bKey = new Byte[32];
                Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);
                Byte[] bVector = new Byte[16];
                Array.Copy(Encoding.UTF8.GetBytes(Vector.PadRight(bVector.Length)), bVector, bVector.Length);
                Byte[] original = null; // Decrypted plaintext  
                Rijndael Aes = Rijndael.Create();
                //add 
                Aes.Mode = CipherMode.CBC;//des in other languages
                Aes.BlockSize = 128;
                Aes.Padding = PaddingMode.PKCS7;
                //add end
                try
                {
                    // Open up a memory stream to store ciphertext  
                    using (MemoryStream Memory = new MemoryStream(encryptedBytes))
                    {
                        //Wrap the memory stream object into an encrypted stream object  
                        using (CryptoStream Decryptor = new CryptoStream(Memory,
                        Aes.CreateDecryptor(bKey, bVector),
                        CryptoStreamMode.Read))
                        {
                            // Plaintext storage area  
                            using (MemoryStream originalMemory = new MemoryStream())
                            {
                                Byte[] Buffer = new Byte[1024];
                                Int32 readBytes = 0;
                                while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0)
                                {
                                    originalMemory.Write(Buffer, 0, readBytes);
                                }
                                original = originalMemory.ToArray();
                            }
                        }
                    }
                }
                catch
                {
                    original = null;
                }
                return Encoding.UTF8.GetString(original);
            }
            catch { return null; }
        }

        /// <summary>
        ///AES base64 encryption key 16 bit or 32 bit
        /// </summary>
        ///< param name = "value" > plaintext string to be encrypted < / param >
        ///< param name = "key" > 16 bit or 32-bit key < / param >
        ///< param name = "IV" > vectors with more than 16 bits; The default is: "* gc_yy_cq_ @ _ztl_99 *" < / param >
        ///< returns > ciphertext encrypted by AES < / returns >
        public static string AesEncrypt(string value, string key, string iv = "")
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;
            if (string.IsNullOrEmpty(key))
            {
                key = Key;
            }
            if (key.Length < 16) throw new Exception("The specified key length cannot be less than 16 bits.");
            if (key.Length > 32) throw new Exception("The specified key length cannot be more than 32 bits.");
            if (key.Length != 16 && key.Length != 24 && key.Length != 32) throw new Exception("The specified key length is ambiguous.");
            if (string.IsNullOrEmpty(iv))
            {
                iv = vector;
            }
            if (!string.IsNullOrEmpty(iv))
            {
                if (iv.Length < 16) throw new Exception("The specified vector length cannot be less than 16 bits.");
            }

            var _keyByte = Encoding.UTF8.GetBytes(key);
            var _valueByte = Encoding.UTF8.GetBytes(value);
            using (var aes = new RijndaelManaged())
            {
                aes.IV = !string.IsNullOrEmpty(iv) ? Encoding.UTF8.GetBytes(iv) : Encoding.UTF8.GetBytes(key.Substring(0, 16));
                aes.Key = _keyByte;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                var cryptoTransform = aes.CreateEncryptor();
                var resultArray = cryptoTransform.TransformFinalBlock(_valueByte, 0, _valueByte.Length);
                return Convert.ToBase64String(resultArray, 0, resultArray.Length);
            }
        }

        /// <summary>
        ///Key 16 bit or 32-bit AES base64 decryption
        /// </summary>
        ///< param name = "value" > ciphertext to be decrypted < / param >
        ///< param name = "key" > the 16 bit or 32-bit key must be consistent with the encryption key < / param >
        ///< param name = "IV" > vectors with more than 16 bits shall be consistent with the vectors during encryption; The default is: "* gc_yy_cq_ @ _ztl_99 *" < / param >
        ///< returns > plaintext after AES decryption < / returns >
        public static string AesDecrypt(string value, string key, string iv = "")
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;
            if (string.IsNullOrEmpty(key))
            {
                key = Key;
            }
            if (key.Length < 16) throw new Exception("The specified key length cannot be less than 16 bits.");
            if (key.Length > 32) throw new Exception("The specified key length cannot be more than 32 bits.");
            if (key.Length != 16 && key.Length != 24 && key.Length != 32) throw new Exception("The specified key length is ambiguous.");
            if (string.IsNullOrEmpty(iv))
            {
                iv = vector;
            }
            if (!string.IsNullOrEmpty(iv))
            {
                if (iv.Length < 16) throw new Exception("The specified vector length cannot be less than 16 bits.");
            }

            var _keyByte = Encoding.UTF8.GetBytes(key);
            var _valueByte = Convert.FromBase64String(value);
            using (var aes = new RijndaelManaged())
            {
                aes.IV = !string.IsNullOrEmpty(iv) ? Encoding.UTF8.GetBytes(iv) : Encoding.UTF8.GetBytes(key.Substring(0, 16));
                aes.Key = _keyByte;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.PKCS7;
                var cryptoTransform = aes.CreateDecryptor();
                var resultArray = cryptoTransform.TransformFinalBlock(_valueByte, 0, _valueByte.Length);
                return Encoding.UTF8.GetString(resultArray);
            }
        }
        #endregion

7, RSA encryption and decryption: adopt the mode of public key and private key

  • RSA encryption adopts the mode of public key encryption and private key decryption or the mode of private key encryption and public key decryption. The digital certificate of Https is also encrypted using this mode.
  • However, RSA encryption has a characteristic, that is, it has a length limit on the encrypted string; The number of bytes to be encrypted cannot exceed the length of the key divided by 8 and then minus 11 (i.e. rsacryptoserviceprovider.keysize/8 - 11). The number of bytes of the ciphertext obtained after encryption is exactly the length of the key divided by 8 (i.e. rsacryptoserviceprovider.keysize/8). Note: this length refers to the length of byte [] array, not the length of string. In short, the encrypted string cannot be too long.
        #region RSA encryption and decryption: the mode of public key and private key is adopted

        #region private key encryption, public key decryption

        /// <summary>
        ///RSA private key encryption
        /// </summary>
        ///< param name = "privatekey" > RSA private key base64 format in Java format < / param >
        ///< param name = "contentdata" > data to be encrypted; Call the method encoding GetEncoding("UTF-8"). GetBytes(contentData)</param>
        ///< param name = "algorithm" > encryption algorithm < / param >
        ///< returns > ciphertext after RSA private key encryption < / returns >
        public static string EncryptWithPrivateKey(string privateKey, byte[] contentData, string algorithm = "RSA/ECB/PKCS1Padding")
        {
            return Convert.ToBase64String(EncryptWithPrivateKey(Convert.FromBase64String(privateKey), contentData, algorithm));
        }

        private static byte[] Transform(AsymmetricKeyParameter key, byte[] contentData, string algorithm, bool forEncryption)
        {
            var c = CipherUtilities.GetCipher(algorithm);
            c.Init(forEncryption, new ParametersWithRandom(key));
            return c.DoFinal(contentData);
        }

        /// <summary>
        ///RSA private key encryption
        /// </summary>
        ///< param name = "privatekey" > RSA private key in Java format < / param >
        ///< param name = "contentdata" > data to be encrypted; Call the method encoding GetEncoding("UTF-8"). GetBytes(contentData)</param>
        ///< param name = "algorithm" > encryption algorithm < / param >
        ///< returns > ciphertext after RSA private key encryption < / returns >
        public static byte[] EncryptWithPrivateKey(byte[] privateKey, byte[] contentData, string algorithm = "RSA/ECB/PKCS1Padding")
        {
            RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privateKey);
            return Transform(privateKeyParam, contentData, algorithm, true);
        }

        /// <summary>
        ///RSA public key decryption
        /// </summary>
        ///< param name = "publickey" > RSA public key base64 format in Java format < / param >
        ///< param name = "content" > base64 format of data to be decrypted < / param >
        ///< param name = "encoding" > decrypted data encoding format, default UTF-8 < / param >
        ///< param name = "algorithm" > encryption algorithm < / param >
        ///< returns > plaintext after RSA private key decryption < / returns >
        public static string DecryptWithPublicKey(string publicKey, string content, string encoding = "UTF-8", string algorithm = "RSA/ECB/PKCS1Padding")
        {
            return Encoding.GetEncoding(encoding).GetString(DecryptWithPublicKey(Convert.FromBase64String(publicKey), Convert.FromBase64String(content), algorithm));
        }

        /// <summary>
        ///RSA public key decryption
        /// </summary>
        ///< param name = "publickey" > RSA public key in Java format < / param >
        ///< param name = "contentdata" > data to be decrypted < / param >
        ///< param name = "algorithm" > encryption algorithm < / param >
        ///< returns > plaintext after RSA private key decryption < / returns >
        public static byte[] DecryptWithPublicKey(byte[] publicKey, byte[] contentData, string algorithm = "RSA/ECB/PKCS1Padding")
        {
            RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(publicKey);
            return Transform(publicKeyParam, contentData, algorithm, false);
        }
        #endregion

        #region public key encryption, private key decryption

        /// <summary>
        ///RSA public key encryption
        /// </summary>
        ///< param name = "xmlpublickey" > encrypt public key; If it is blank, the default system public key is < / param >
        ///< param name = "enptstr" > plaintext string to be encrypted < / param >
        ///< param name = "encoding" > encoding format; Default: UTF-8 < / param >
        ///< returns > ciphertext encrypted by RSA public key < / returns >
        public static string RSAEncrypt_Public(string xmlPublicKey, string enptStr, string encoding = "UTF-8")
        {
            if (string.IsNullOrEmpty(xmlPublicKey))
            {
                xmlPublicKey = _publicKey;
            }
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                byte[] cipherbytes;
                rsa.FromXmlString(xmlPublicKey);
                cipherbytes = rsa.Encrypt(Encoding.GetEncoding(encoding).GetBytes(enptStr), false);
                return Convert.ToBase64String(cipherbytes);
            }
        }

        /// <summary>
        ///RSA private key decryption
        /// </summary>
        ///< param name = "xmlprivatekey" > decrypt the private key; If it is blank, the default system public key is < / param >
        ///< param name = "enptstr" > plaintext string to be encrypted < / param >
        ///< param name = "encoding" > encoding format; Default: UTF-8 < / param >
        ///< returns > plaintext decrypted by RSA private key < / returns >
        public static string RSADecrypt_Private(string xmlPrivateKey, string enptStr, string encoding = "UTF-8")
        {
            if (string.IsNullOrEmpty(xmlPrivateKey))
            {
                xmlPrivateKey = _privateKey;
            }
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                byte[] cipherbytes;
                rsa.FromXmlString(xmlPrivateKey);
                cipherbytes = rsa.Decrypt(Convert.FromBase64String(enptStr), false);
                return Encoding.GetEncoding(encoding).GetString(cipherbytes);
            }
        }
        #endregion

        #region uses the name of the same container for RSA encryption and decryption

        /// <summary>
        ///RSA encryption
        /// </summary>
        ///< param name = "sourcestr" > source string < / param >
        ///< returns > encrypted string < / returns >
        public static string RsaEncrypt(string sourceStr)
        {
            Param = new CspParameters();
            //The name of the key container. Only when the encryption and decryption are consistent can the decryption be successful
            Param.KeyContainerName = "Navis";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(Param))
            {
                //Converts the string to be encrypted into a byte array
                byte[] plaindata = Encoding.Default.GetBytes(sourceStr);
                //Encryption via byte array
                byte[] encryptdata = rsa.Encrypt(plaindata, false);
                //Convert the encrypted byte array into a string
                return Convert.ToBase64String(encryptdata);
            }
        }

        /// <summary>
        ///Decryption via RSA encryption
        /// </summary>
        ///< param name = "codingstr" > encrypted string < / param >
        ///< returns > decrypted string < / returns >
        public static string RsaDesEncrypt(string codingStr)
        {
            Param = new CspParameters();
            Param.KeyContainerName = "Navis";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(Param))
            {
                byte[] encryptdata = Convert.FromBase64String(codingStr);
                byte[] decryptdata = rsa.Decrypt(encryptdata, false);
                return Encoding.Default.GetString(decryptdata);
            }
        }
        #endregion

        #region RSA segmented encryption: the string to be encrypted is disassembled, the length of each segment is less than or equal to the limit length, and then segmented encryption

        /// <summary>
        ///RSA segmented encryption
        /// </summary>
        ///< param name = "xmlpublickey" > RSA c# public key < / param >
        ///< param name = "enptstr" > long string requiring RSA encryption < / param >
        ///< returns > returns the ciphertext encrypted by RSA < / returns >
        public static String SubRSAEncrypt(string xmlPublicKey, string enptStr)
        {
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            provider.FromXmlString(xmlPublicKey);
            Byte[] bytes = Encoding.Default.GetBytes(enptStr);
            int MaxBlockSize = provider.KeySize / 8 - 11;  //Maximum length limit of encryption block

            if (bytes.Length <= MaxBlockSize)
                return Convert.ToBase64String(provider.Encrypt(bytes, false));

            using (MemoryStream PlaiStream = new MemoryStream(bytes))
            using (MemoryStream CrypStream = new MemoryStream())
            {
                Byte[] Buffer = new Byte[MaxBlockSize];
                int BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);

                while (BlockSize > 0)
                {
                    Byte[] ToEncrypt = new Byte[BlockSize];
                    Array.Copy(Buffer, 0, ToEncrypt, 0, BlockSize);

                    Byte[] Cryptograph = provider.Encrypt(ToEncrypt, false);
                    CrypStream.Write(Cryptograph, 0, Cryptograph.Length);

                    BlockSize = PlaiStream.Read(Buffer, 0, MaxBlockSize);
                }

                return Convert.ToBase64String(CrypStream.ToArray(), Base64FormattingOptions.None);
            }

        }

        /// <summary>
        ///RSA segmented decryption to deal with long strings
        /// </summary>
        ///< param name = "xmlprivatekey" > RSA c# private key < / param >
        ///< param name = "enptstr" > long string to be decrypted < / param >
        ///< returns > returns the plaintext decrypted by RSA segment < / returns >
        public static String SubRSADecrypt(string xmlPrivateKey, string enptStr)
        {
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            provider.FromXmlString(xmlPrivateKey);
            Byte[] bytes = Convert.FromBase64String(enptStr);
            int MaxBlockSize = provider.KeySize / 8;  //Maximum decryption block length limit

            if (bytes.Length <= MaxBlockSize)
                return Encoding.Default.GetString(provider.Decrypt(bytes, false));

            using (MemoryStream CrypStream = new MemoryStream(bytes))
            using (MemoryStream PlaiStream = new MemoryStream())
            {
                Byte[] Buffer = new Byte[MaxBlockSize];
                int BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);

                while (BlockSize > 0)
                {
                    Byte[] ToDecrypt = new Byte[BlockSize];
                    Array.Copy(Buffer, 0, ToDecrypt, 0, BlockSize);

                    Byte[] Plaintext = provider.Decrypt(ToDecrypt, false);
                    PlaiStream.Write(Plaintext, 0, Plaintext.Length);

                    BlockSize = CrypStream.Read(Buffer, 0, MaxBlockSize);
                }

                return Encoding.Default.GetString(PlaiStream.ToArray());
            }
        }
        #endregion

        #endregion

This article is from the blog Park and written by: TomLucas For reprint, please indicate the original link

Topics: C# linq