SoFunction
Updated on 2025-03-01

Detailed explanation of C# implementation of encryption and decryption

1. Hash encryption, using the derived classes of HashAlgorithm hash algorithm class (MD5, SHA1, etc.)

Features: Only encrypted, irreversible. A unique Hash value of a specific length can be generated for the target information.

HashAlgorithm derived classes include:

  • KeyedHashAlgorithm: Shows abstract classes from which all cryptographic hash algorithm implementations must derive.
  • MD5: Represents an abstract class from which all implementations of the MD5 hash algorithm are inherited.
    ————MD5Crypto​Service​Provider: Calculate the MD5 hash of the input data using an implementation provided by the Crypto Service Provider (CSP).
  • RIPEMD160: An abstract class that represents an abstract class from which all implementations of the MD160 hash algorithm are inherited.
  • SHA1: Calculate the SHA1 hash value of the input data.
    ————SHA1Crypto​Service​Provider: Calculate the SHA1 hash of the input data using an implementation provided by the Crypto Service Provider (CSP).
  • SHA256: Calculates the SHA256 hash value of the input data.
  • SHA384: Calculates the SHA384 hash value of the input data.
  • SHA512: Calculates the SHA512 hash value of the input data.

1. Use the abstract class HashAlgorithm

//The plain text password is converted from a string to a byte arraybyte[] clearBytes =("123");

// Calculate the MD5 ciphertext byte array from the plaintext byte arraybyte[] hashedBytes = ((HashAlgorithm)("MD5")).ComputeHash(clearBytes);
//Convert the byte array to a string and return it. BitConverter is used to convert the basic data type and the byte array to each other.string result = (hashedBytes).Replace("-", "");

(result);

2. Use abstract class MD5

byte[] clearBytes = ("123");
byte[] hashedBytes =  ().ComputeHash(clearBytes);

StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < ; i++)
{
    (hashedBytes[i].ToString("x2"));
}
string result = ();
(result);

3. Use MD5CryptoServiceProvider class

byte[] clearBytes = ("123");
byte[] hashedBytes = new MD5CryptoServiceProvider().ComputeHash(clearBytes);
string result = "";
for (int i = 0; i < ; i++)
    result += hashedBytes[i].ToString("X").PadLeft(2, '0');

(result);

4. Hash encryption used by the web: FormsAuthentication class

(str,"MD5")//or“SHA1”

5. File hash calculation

  • MD5 is a one-way operation that converts a data string of any length into a short fixed-length value. Any two strings should not have the same hash value (i.e., it is "very likely" to be different, and it should be difficult to artificially create two strings with the same hash value).
  • Therefore, MD5 is often used to verify strings or files, because if the MD5 of the file is different, it means that the content of the file is also different, that is, it has been modified. If you find that the downloaded file is different from the given md5 value, you need to use it carefully.
  • MD5 file verification has many uses, such as: verification of game patch packages, virus file confirmation, app review verification, etc. As long as you need to confirm the uniqueness and correctness of a certain file, md5 will be used as verification.

Enter the file path and you can get the corresponding hash value. This hash value is related to the content of the file itself, including the file name, and has nothing to do with the file storage path, the running platform, and the device.

string GetFileHash(string path)
{
    var hash = ();//();
    var stream = new FileStream(path, );
    byte[] hashByte = (stream);
    ();
    return (hashByte).Replace("-", "");
}

2. Symmetric encryption: Derived classes (Aes, DES, etc.) using SymmetricAlgorithm symmetric algorithm class

Features: refers to encryption algorithms that use the same key to encryption and decryption.

The advantages of symmetric encryption algorithms are the high speed of encryption and decryption and the difficulty of cracking when using long keys.

SymmetricAlgorithm derived classes include:

  • Aes: Represents an abstract base class from which all implementations of the Advanced Encryption Standard (AES) must inherit.
    ————Aes​Crypto​Service​Provider: Encryption Application Programming Interface (CAPI) implementation using Advanced Encryption Standard (AES) algorithms to perform symmetric encryption and decryption.
  • DES: The base class of the Data Encryption Standard (DES) algorithm from which all DES implementations must derive.
    ————DESCrypto​Service​Provider: Defines the wrapper object for the encryption service provider (CSP) version of the access data encryption standard (DES) algorithm.
  • RC2: represents the base class from which all implementations of the RC2 algorithm must derive.
  • Rijndael: represents the base class from which all implementations of Rijndael symmetric encryption algorithm must inherit.
  • TripleDES: The base class representing the standard algorithm for triple data encryption
public static string strKey = "abcdefgh";//Note: The key sKey here must be converted to 8 bytes, that is, the input key is 8 half-width characters or 4 full-width characters or 4 Chinese characters stringspublic static string strIV = "ijklmnop";

// Encryptionpublic static string Encrypt(string _strQ)
{
    byte[] buffer = Encoding.(_strQ);
    MemoryStream ms = new MemoryStream();
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    CryptoStream encStream = new CryptoStream(ms, (Encoding.(strKey), Encoding.(strIV)), );
    (buffer, 0, );
    ();
    return Convert.ToBase64String(());
}

// Decryptpublic static string Decrypt(string _strQ)
{
    byte[] buffer = Convert.FromBase64String(_strQ);
    MemoryStream ms = new MemoryStream();
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    CryptoStream encStream = new CryptoStream(ms, (Encoding.(strKey), Encoding.(strIV)), );
    (buffer, 0, );
    ();
    return Encoding.(());
}

3. Asymmetric encryption: derived classes (DSA, RSA, etc.) using Asymmetric Algorithm asymmetric algorithm class

Features: refers to encryption algorithms that use different keys to encrypt and decrypt, also known as public-private key encryption. The public key can be used for encryption publicly, and the private key is strictly confidential by the recipient for encryption.

The disadvantage of asymmetric encryption is that the encryption and decryption speed is much slower than symmetric encryption.

The AsymmetricAlgorithm derived classes include:

  • DSA: Represents an abstract base class from which all implementations of digital signature algorithms (DSAs) must inherit.
    ————DSACryptoServiceProvider: Use the implementation of the DSA algorithm provided by the Crypto Service Provider (CSP) to perform asymmetric encryption and decryption.
  • ECDiffie​Hellman:
  • ECDsa:
  • RSA: Represents the base class from which all implementations of the RSA algorithm are inherited.
    ————RSACrypto​Service​Provider: Perform asymmetric encryption and decryption using the implementation of RSA algorithms provided by the Crypto Service Provider (CSP).
/// 

/// To obtain the key used for encryption, the RSA algorithm is an asymmetric cryptographic algorithm. The so-called asymmetry means that the algorithm requires a pair of keys. If one of them is encrypted, the other needs to be used to decrypt it./// 
public static void GetKey()
{
    string PublicKey = ;
    string PrivateKey = ;
    RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider();
    PublicKey = (false);
    // Get the public key for encryption    PrivateKey = (true);
    // Get public and private keys for decryption
    //("PublicKey is {0}", PublicKey); // Output public key    //("PrivateKey is {0}", PrivateKey); // Output key    //The key contains a public key, and the public key is calculated based on the password.
    using (StreamWriter streamWriter = new StreamWriter(""))
    {
        ((false));// Save the public key to PublicKey in the run directory    }
    using (StreamWriter streamWriter = new StreamWriter(""))
    {
        ((true)); // Save the public and private keys to PrivateKey in the run directory    }
}

/// 

/// Encryption/// 
private static string Encryption(string str)
{
    RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider();
    using (StreamReader streamReader = new StreamReader("")) // Read the running directory    {
        (()); // Load the public key into the RSA instance    }

    byte[] buffer = Encoding.(str); // Convert plaintext to byte[]
    // The encrypted data is an array of byte[], which can be saved in the form of a file or in other forms (many tutorials on the Internet, using Base64 for encoding and saving)    byte[] EncryptBuffer = (buffer, false); // Encryption    return Convert.ToBase64String(EncryptBuffer); // If you use base64 for explicit culture, you need to convert base64 to byte[] again when decrypting}

/// 

/// Decrypt/// 
private static string Decrypt(string strEncryptBase64)
{
    RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider();
    using (StreamReader streamReader = new StreamReader("")) // Read the running directory    {
        (()); // Load the private key into the RSA instance    }

    byte[] buffer = Convert.FromBase64String(strEncryptBase64);
    // After decryption, get a byte[] array    byte[] DecryptBuffer = (buffer, false); // Decrypt    string str = Encoding.(DecryptBuffer); // Convert byte[] to plaintext
    return str;
}

This is all about this article about C# encryption and decryption. I hope it will be helpful to everyone's learning and I hope everyone will support me more.