C# commonly used encryption and decryption algorithms

1 Introduction

In software development, data security and confidentiality are very important. To protect data from unauthorized access and disclosure, we often need to encrypt and decrypt sensitive data. In C#, there are many common encryption and decryption methods to choose from. This article will introduce in detail the encryption and decryption methods commonly used in C#.
Insert image description here



2. Symmetric encryption algorithm

Symmetric encryption algorithms use the same key to encrypt and decrypt data. The following are two symmetric encryption algorithms commonly used in C#:

2.1 DES encryption algorithm

DES (Data Encryption Standard) is a symmetric encryption algorithm that uses a 56-bit key to encrypt and decrypt data. Here is an example using the DES encryption algorithm:

using System;
using System.Security.Cryptography;
using System.Text;

public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        string plainText = "Hello, World!";
        string key = "mysupersecretkey";
        
        byte[] encryptedData = EncryptDES(plainText, key);
        string decryptedData = DecryptDES(encryptedData, key);
        
        Console.WriteLine($"Original data: {
      
      plainText}");
        Console.WriteLine($"Encrypted data: {
      
      Convert.ToBase64String(encryptedData)}");
        Console.WriteLine($"Decrypted data: {
      
      decryptedData}");
    }
    
    static byte[] EncryptDES(string plainText, string key)
    {
    
    
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);

        using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
        {
    
    
            cryptoProvider.Key = keyBytes;
            cryptoProvider.Mode = CipherMode.ECB;

            using (ICryptoTransform encryptor = cryptoProvider.CreateEncryptor())
            {
    
    
                return encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
            }
        }
    }
    
    static string DecryptDES(byte[] encryptedData, string key)
    {
    
    
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);

        using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
        {
    
    
            cryptoProvider.Key = keyBytes;
            cryptoProvider.Mode = CipherMode.ECB;

            using (ICryptoTransform decryptor = cryptoProvider.CreateDecryptor())
            {
    
    
                byte[] plainBytes = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
                return Encoding.UTF8.GetString(plainBytes);
            }
        }
    }
}

The above code first calls the EncryptDES method using the key and plaintext data to encrypt, and then calls the DecryptDES method using the key and encrypted data to decrypt.

Insert image description here

2.2 AES encryption algorithm

AES (Advanced Encryption Standard) is a symmetric encryption algorithm that uses 128, 192 or 256-bit keys to encrypt and decrypt data. Here is an example using the AES encryption algorithm:

using System;
using System.Security.Cryptography;
using System.Text;

public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        string plainText = "Hello, World!";
        string key = "mysupersecretkey";

        byte[] encryptedData = EncryptAES(plainText, key);
        string decryptedData = DecryptAES(encryptedData, key);

        Console.WriteLine($"Original data: {
      
      plainText}");
        Console.WriteLine($"Encrypted data: {
      
      Convert.ToBase64String(encryptedData)}");
        Console.WriteLine($"Decrypted data: {
      
      decryptedData}");
    }

    static byte[] EncryptAES(string plainText, string key)
    {
    
    
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);

        using (AesCryptoServiceProvider cryptoProvider = new AesCryptoServiceProvider())
        {
    
    
            cryptoProvider.Key = keyBytes;

            cryptoProvider.GenerateIV();
            byte[] iv = cryptoProvider.IV;

            using (ICryptoTransform encryptor = cryptoProvider.CreateEncryptor())
            {
    
    
                byte[] encryptedBytes = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);

                byte[] encryptedData = new byte[encryptedBytes.Length + iv.Length];
                Array.Copy(iv, 0, encryptedData, 0, iv.Length);
                Array.Copy(encryptedBytes, 0, encryptedData, iv.Length, encryptedBytes.Length);

                return encryptedData;
            }
        }
    }

    static string DecryptAES(byte[] encryptedData, string key)
    {
    
    
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);

        using (AesCryptoServiceProvider cryptoProvider = new AesCryptoServiceProvider())
        {
    
    
            int ivSize = cryptoProvider.BlockSize / 8;
            byte[] iv = new byte[ivSize];
            Array.Copy(encryptedData, 0, iv, 0, ivSize);

            cryptoProvider.Key = keyBytes;
            cryptoProvider.IV = iv;

            using (ICryptoTransform decryptor = cryptoProvider.CreateDecryptor())
            {
    
    
                byte[] encryptedBytes = new byte[encryptedData.Length - ivSize];
                Array.Copy(encryptedData, ivSize, encryptedBytes, 0, encryptedBytes.Length);

                byte[] plainBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
                return Encoding.UTF8.GetString(plainBytes);
            }
        }
    }
}

The above code first calls the EncryptAES method using the key and plaintext data to encrypt, and then calls the DecryptAES method using the key and encrypted data to decrypt. The AES encryption algorithm also requires the use of an initialization vector (IV), which is used to increase the randomness of encryption.
Insert image description here


3. Asymmetric encryption algorithm

Asymmetric encryption algorithms use a pair of public and private keys for encryption and decryption. The following are asymmetric encryption algorithms commonly used in C#:

3.1 RSA encryption algorithm

RSA (Rivest-Shamir-Adleman) is an asymmetric encryption algorithm that uses a public key to encrypt data and a private key to decrypt data. Here is an example using the RSA encryption algorithm:

using System;
using System.Security.Cryptography;
using System.Text;

public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        string plainText = "Hello, World!";

        byte[] encryptedData = EncryptRSA(plainText);
        string decryptedData = DecryptRSA(encryptedData);

        Console.WriteLine($"Original data: {
      
      plainText}");
        Console.WriteLine($"Encrypted data: {
      
      Convert.ToBase64String(encryptedData)}");
        Console.WriteLine($"Decrypted data: {
      
      decryptedData}");
    }

    static byte[] EncryptRSA(string plainText)
    {
    
    
        using (RSACryptoServiceProvider cryptoProvider = new RSACryptoServiceProvider())
        {
    
    
            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
            return cryptoProvider.Encrypt(plainBytes, true);
        }
    }

    static string DecryptRSA(byte[] encryptedData)
    {
    
    
        using (RSACryptoServiceProvider cryptoProvider = new RSACryptoServiceProvider())
        {
    
    
            byte[] plainBytes = cryptoProvider.Decrypt(encryptedData, true);
            return Encoding.UTF8.GetString(plainBytes);
        }
    }
}

The above code first uses the public key to encrypt the plaintext data by calling the EncryptRSA method, and then uses the private key and encrypted data to call the DecryptRSA method to decrypt.
Insert image description here


4. Hash algorithm

Hashing algorithms convert arbitrary length data into fixed-length hash values. The following are hashing algorithms commonly used in C#:

4.1 MD5 hash algorithm

MD5 (Message Digest Algorithm 5) is a common hash algorithm that converts data of any length into a 128-bit hash value. Here is an example using the MD5 hashing algorithm:

using System;
using System.Security.Cryptography;
using System.Text;

public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        string plainText = "Hello, World!";

        string hash = HashMD5(plainText);

        Console.WriteLine($"Original data: {
      
      plainText}");
        Console.WriteLine($"Hash value: {
      
      hash}");
    }

    static string HashMD5(string plainText)
    {
    
    
        byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);

        using (MD5 cryptoProvider = new MD5CryptoServiceProvider())
        {
    
    
            byte[] hashBytes = cryptoProvider.ComputeHash(plainBytes);
            StringBuilder hashBuilder = new StringBuilder();

            foreach (byte b in hashBytes)
            {
    
    
                hashBuilder.Append(b.ToString("x2"));
            }

            return hashBuilder.ToString();
        }
    }
}

The above code uses the HashMD5 method to calculate the hash value of the given plaintext data and converts the result into a hexadecimal string.
Insert image description here

4.2 SHA hashing algorithm

SHA (Secure Hash Algorithm) is a series of hash algorithms, including SHA-1, SHA-256, SHA-384 and SHA-512. Compared with MD5, the SHA series of algorithms are more secure. Here is an example using the SHA-256 hashing algorithm:

using System;
using System.Security.Cryptography;
using System.Text;

public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        string plainText = "Hello, World!";

        string hash = HashSHA256(plainText);

        Console.WriteLine($"Original data: {
      
      plainText}");
        Console.WriteLine($"Hash value: {
      
      hash}");
    }

    static string HashSHA256(string plainText)
    {
    
    
        byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);

        using (SHA256 cryptoProvider = new SHA256CryptoServiceProvider())
        {
    
    
            byte[] hashBytes = cryptoProvider.ComputeHash(plainBytes);
            StringBuilder hashBuilder = new StringBuilder();

            foreach (byte b in hashBytes)
            {
    
    
                hashBuilder.Append(b.ToString("x2"));
            }

            return hashBuilder.ToString();
        }
    }
}

The above code uses the HashSHA256 method to calculate the hash value of the given plaintext data and converts the result into a hexadecimal string.
Insert image description here


5. Summary

This article details encryption and decryption methods commonly used in C#, including symmetric encryption algorithms (such as DES and AES), asymmetric encryption algorithms (such as RSA), and hashing algorithms (such as MD5 and SHA). By rationally selecting encryption algorithms and methods suitable for the scenario, we can effectively protect the security and confidentiality of data. I hope this article will help you use encryption and decryption methods in C# development.

Guess you like

Origin blog.csdn.net/qq_22120623/article/details/135082799