SoFunction
Updated on 2025-03-01

Examples of encryption and decryption methods commonly used in C# development

Preface

I believe that many people often encounter the need to encrypt some important information during the development process. Today I will share with you some encryption algorithms I have personally summarized:

Common encryption methods are divided into two types: reversible and irreversible

Reversible: RSA, AES, DES, etc.

Irreversible: Common MD5, SHAD, etc.

1. MD5 message digest algorithm

I think this is an algorithm that everyone has heard of frequently and may also be used more. So what is the MD5 algorithm? The full name of MD5 is message-digest algorithm 5. In short, it is one-way encryption, which means that plain text cannot be derived from ciphertexts.

Main uses of MD5:

1. Generate an information summary for a piece of information. The summary is unique to the information and can be used as a digital signature.

2. Used to verify the validity of the file (whether there is lost or corrupt data)

3. Encrypting the user's password

4. Calculate the hash value in the hash function

From the main uses above, we see that due to some irreversible features of the algorithm, there is better security in encryption applications. By using the MD5 encryption algorithm, we input a byte string of any length and will generate a 128-bit integer. So according to this point MD5 is widely used as password encryption. Below I will demonstrate how to encrypt passwords.

First, we need to introduce a namespace, and first look at a relatively simple example of MD5 encryption:

using ;

using ;

public string ToMD5(string strs) 
{
      MD5 md5 = new MD5CryptoServiceProvider();
      byte[] bytes = (strs);//Convert the string to be encrypted into a byte array      byte[] encryptdata = (bytes);//Encrypt the string and convert it into a character array      return Convert.ToBase64String(encryptdata);//Convert the encrypted byte array into an encrypted string }

What we need to note here is that no matter during the encryption process, the encrypted string should be converted into a byte array before encryption, and after encryption, the byte data of the ciphertext should be generated, and then converted into the ciphertext.

Here are other forms of MD5 encryption, you can write the encryption algorithm you need according to your needs:

/// <summary>
    /// Create hash strings for creating 32-character hexadecimal format hash strings on any MD5 hash function (on any platform)    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static string Get32MD5One(string source)
    {
      using (.MD5 md5Hash = .())
      {
        byte[] data = (.(source));
         sBuilder = new ();
        for (int i = 0; i < ; i++)
        {
          (data[i].ToString("x2"));
        }

        string hash = ();
        return ();
      }
    }

    /// <summary>
    /// Get 16-bit md5 encryption    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static string Get16MD5One(string source)
    {
      using (.MD5 md5Hash = .())
      {
        byte[] data = (.(source));
        //Convert to string and take 9 to 25 bits        string sBuilder = (data, 4, 8);
        //The string converted from BitConverter will generate a separator in the middle of each character, which needs to be removed        sBuilder = ("-", "");
        return ().ToUpper();
      }
    }

    //// <summary>
    /// </summary>
    /// <param name="strSource">Plaintext that requires encryption</param>    /// <returns>Returns 32-bit encryption result, which takes the 9th to 25th bits of the 32-bit encryption result</returns>    public static string Get32MD5Two(string source)
    {
      .MD5 md5 = new .MD5CryptoServiceProvider();
      //Get password byte array      byte[] bytResult = ((source));
      //Convert to string, 32 bit      string strResult = (bytResult);
      //The string converted from BitConverter will generate a separator in the middle of each character, which needs to be removed      strResult = ("-", "");
      return ();
    }

    //// &lt;summary&gt;
    /// &lt;/summary&gt;
    /// <param name="strSource">Plaintext that requires encryption</param>    /// <returns>Returns 16-bit encryption result, which takes the 9th to 25th bits of the 32-bit encryption result</returns>    public static string Get16MD5Two(string source)
    {
      .MD5 md5 = new .MD5CryptoServiceProvider();
      //Get password byte array      byte[] bytResult = ((source));
      //Convert to string and take 9 to 25 bits      string strResult = (bytResult, 4, 8);
      //The string converted from BitConverter will generate a separator in the middle of each character, which needs to be removed      strResult = ("-", "");
      return ();
    }

2. DES encryption

The DES encryption algorithm is a symmetric cryptographic system in the cryptographic system, also known as the American data encryption standard. It is a symmetric cryptographic system encryption algorithm developed by IBM in the United States in 1972. The plaintext is grouped by 64 bits, and the key is actually a cryptographic method that forms a ciphertext group by 56 bits participating in DES operations (8th, 16, 24, 32, 40, 48, 56, 64 bits, so that each key has an odd number of 1s) and a 56-bit key after the grouping are bit substitution or exchanged.

DES, full name Data Encryption Standard, is a symmetric encryption algorithm. Because of its high security (without a limited time, there is no encryption method that can be said to be 100% secure), it is likely to be the most extensive key system (our company is also using it, and I guess you are using it too...). The only way to crack this algorithm is the exhaustive method.

/// &lt;summary&gt;
    /// DES encryption    /// &lt;/summary&gt;
    /// <param name="data">Encrypted data</param>    /// <param name="key">8-bit character key string</param>    /// <param name="iv">Initialization vector string for 8-bit characters</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static string DESEncrypt(string data, string key, string iv)
    {
      byte[] byKey = (key);
      byte[] byIV = (iv);

      DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
      int i = ;
      MemoryStream ms = new MemoryStream();
      CryptoStream cst = new CryptoStream(ms, (byKey, byIV), );

      StreamWriter sw = new StreamWriter(cst);
      (data);
      ();
      ();
      ();
      return Convert.ToBase64String((), 0, (int));
    }

    /// &lt;summary&gt;
    /// DES decryption    /// &lt;/summary&gt;
    /// <param name="data">Decrypt data</param>    /// <param name="key">8-bit character key string (same as when encrypted)</param>    /// <param name="iv">Initialization vector string for 8-bit characters (the same as when encrypted)</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static string DESDecrypt(string data, string key, string iv)
    {
      byte[] byKey = (key);
      byte[] byIV = (iv);

      byte[] byEnc;
      try
      {
        byEnc = Convert.FromBase64String(data);
      }
      catch
      {
        return null;
      }

      DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
      MemoryStream ms = new MemoryStream(byEnc);
      CryptoStream cst = new CryptoStream(ms, (byKey, byIV), );
      StreamReader sr = new StreamReader(cst);
      return ();
    }

There is also an AES encryption algorithm, but AES encryption is a new encryption algorithm that can be used to protect electronic data. The password it produces is an iteratively symmetric packet password, using a loop structure in which the input data is repeatedly replaced and replaced.

3. RSA encryption algorithm

Before talking about RSA encryption algorithm, we need to understand the following two professional terms, symmetric encryption and asymmetric encryption.

Symmetric encryption means: contains something called a key. The message is encrypted using a key before the message is sent. After the other party receives the message, the same key is used for decryption.

Asymmetric encryption means encryption algorithms that use different keys to encrypt and decrypt. This type of encryption algorithm usually has two keys A and B. Only key B can decrypt the ciphertext obtained by encrypting the data using key A (even key A cannot decrypt it). On the contrary, only key A can decrypt the ciphertext obtained by encrypting the data using key B. These two keys are called private keys and public keys respectively. As the name implies, private keys are keys that you personally reserve and cannot be disclosed, while public keys are disclosed to the other party of the encryption and decryption operation. Depending on different purposes, the keys used to encrypt data are also different (sometimes they are encrypted with public keys and decrypted with private keys; sometimes they are encrypted with private keys and decrypted with public keys). The representative algorithm of asymmetric encryption is the RSA algorithm.

After understanding these two nouns, the RSA encryption algorithm is discussed below. RSA naming comes from the names that develop the three of them. RSA is currently the most influential public key encryption algorithm, mostly used for data encryption and digital signatures. Although it has such great influence, it also has some disadvantages. It is very troublesome to generate keys and is limited by prime number generation technology, so it is difficult to achieve one density at a time, and the grouping length is too large.

The following example demonstrates the use of RSA encryption, decryption, and reference namespace;

/// &lt;summary&gt; 
    /// RSA encrypted data    /// &lt;/summary&gt; 
    /// <param name="express">To encrypt data</param>    /// <param name="KeyContainerName">Name of the key container</param>    /// &lt;returns&gt;&lt;/returns&gt; 
    public static string RSAEncryption(string express, string KeyContainerName = null)
    {

       param = new ();
       = KeyContainerName ?? "zhiqiang"; //The name of the key container can be successfully decrypted by keeping the encryption and decryption consistent      using ( rsa = new (param))
      {
        byte[] plaindata = (express);//Convert the string to be encrypted into a byte array        byte[] encryptdata = (plaindata, false);//Convert the encrypted byte data into a new encrypted byte array        return Convert.ToBase64String(encryptdata);//Convert the encrypted byte array to a string      }
    }
    /// &lt;summary&gt; 
    /// RSA decrypts data    /// &lt;/summary&gt; 
    /// <param name="express">To decrypt data</param>    /// <param name="KeyContainerName">Name of the key container</param>    /// &lt;returns&gt;&lt;/returns&gt; 
    public static string RSADecrypt(string ciphertext, string KeyContainerName = null)
    {
       param = new ();
       = KeyContainerName ?? "zhiqiang"; //The name of the key container can be successfully decrypted by keeping the encryption and decryption consistent      using ( rsa = new (param))
      {
        byte[] encryptdata = Convert.FromBase64String(ciphertext);
        byte[] decryptdata = (encryptdata, false);
        return (decryptdata);
      }
    }

4. Base64 encoding

I won't explain too much, just upload the code.

#region Base64 encryption and decryption    /// &lt;summary&gt;
    /// Base64 encryption    /// &lt;/summary&gt;
    /// <param name="input">Strings that require encryption</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static string Base64Encrypt(string input)
    {
      return Base64Encrypt(input, new UTF8Encoding());
    }

    /// &lt;summary&gt;
    /// Base64 encryption    /// &lt;/summary&gt;
    /// <param name="input">Strings that require encryption</param>    /// <param name="encode">character encoding</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static string Base64Encrypt(string input, Encoding encode)
    {
      return Convert.ToBase64String((input));
    }

    /// &lt;summary&gt;
    /// Base64 decryption    /// &lt;/summary&gt;
    /// <param name="input">Strings that need to be decrypted</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static string Base64Decrypt(string input)
    {
      return Base64Decrypt(input, new UTF8Encoding());
    }

    /// &lt;summary&gt;
    /// Base64 decryption    /// &lt;/summary&gt;
    /// <param name="input">Strings that need to be decrypted</param>    /// <param name="encode">character encoding</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static string Base64Decrypt(string input, Encoding encode)
    {
      return (Convert.FromBase64String(input));
    }
    #endregion

V. SHA secure hashing algorithm

SHA, full name SecureHashAlgorithm, is a data encryption algorithm. The idea of ​​this algorithm is to receive a plain text and then convert it into a (usually smaller) ciphertext in an irreversible way. It can also be simply understood as the process of taking a string of input codes (called premapping or information) and converting them into a short-length, fixed-digit output sequence, i.e. hash value (also known as information digest or information authentication code).

The following are various encryption algorithm codes for SHA:

//SHA is irreversible encryption    public static string SHA1Encrypt(string Txt)
    {
      var bytes = (Txt);
      var SHA = new .SHA1CryptoServiceProvider();
      var encryptbytes = (bytes);
      return Convert.ToBase64String(encryptbytes);
    }
    public static string SHA256Encrypt(string Txt)
    {
      var bytes = (Txt);
      var SHA256 = new .SHA256CryptoServiceProvider();
      var encryptbytes = (bytes);
      return Convert.ToBase64String(encryptbytes);
    }
    public static string SHA384Encrypt(string Txt)
    {
      var bytes = (Txt);
      var SHA384 = new .SHA384CryptoServiceProvider();
      var encryptbytes = (bytes);
      return Convert.ToBase64String(encryptbytes);
    }
    public string SHA512Encrypt(string Txt)
    {
      var bytes = (Txt);
      var SHA512 = new .SHA512CryptoServiceProvider();
      var encryptbytes = (bytes);
      return Convert.ToBase64String(encryptbytes);
    }

6. AES encryption algorithm

The AES algorithm is based on permutation and permutation operations. Arrangement is to re-arrange data, and permutation is to replace one data unit with another.

AES uses several different methods to perform permutation and permutation operations. AES is an iterative, symmetric key grouping password that can use 128, 192, and 256-bit keys and encrypt and decrypt data with 128-bit (16-byte) packets. Unlike public key passwords that use key pairs, symmetric key passwords use the same key to encrypt and decrypt data. The number of bits of encrypted data returned by the packet password is the same as the input data. Iterative encryption uses a loop structure in which input data is repeatedly replaced and replaced.

/// &lt;summary&gt;
    /// AES encryption    /// &lt;/summary&gt;
    /// <param name="str">Plaintext (to be encrypted)</param>    /// <param name="key">ciphertext</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public string AesEncrypt(string str, string key)
    {
      if ((str)) return null;
      Byte[] toEncryptArray = Encoding.(str);
 
      RijndaelManaged rm = new RijndaelManaged
      {
        Key = Encoding.(key),
        Mode = ,
        Padding = PaddingMode.PKCS7
      };
 
      ICryptoTransform cTransform = ();
      Byte[] resultArray = (toEncryptArray, 0, );
      return Convert.ToBase64String(resultArray);
    }
 
    /// &lt;summary&gt;
    /// AES Decryption    /// &lt;/summary&gt;
    /// <param name="str">Plain text (to be decrypted)</param>    /// <param name="key">ciphertext</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public string AesDecrypt(string str, string key)
    {
      if ((str)) return null;
      Byte[] toEncryptArray = Convert.FromBase64String(str);
 
      RijndaelManaged rm = new RijndaelManaged
      {
        Key = Encoding.(key),
        Mode = ,
        Padding = PaddingMode.PKCS7
      };
 
      ICryptoTransform cTransform = ();
      Byte[] resultArray = (toEncryptArray, 0, );
 
      return Encoding.(resultArray);
    }

OK, that’s all for today’s sharing of common C# encryption algorithms! ! !

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.