How to Encrypt and Decrypt plain string using Triple DES in C#

By FoxLearn 7/20/2024 2:27:07 AM   28.48K
Encrypting and decrypting using Triple DES (Data Encryption Standard) in C# involves several steps.

How to encrypt and decrypt using Triple DES (3DES) algorithm in C#

To create a simple encryption and decryption in c#, you can drag the TextBox, Label and Button controls from the visual studio toolbox to your windows forms application, then you can design a simple UI that allows you to encrypt and decrypt in c# with key using the Triple DES algorithm as shown below.

c# encrypt decrypt using triple des

You need to create an Encrypt method to encrypt your data using Triple DES algorithm.

public string Encrypt(string source, string key)
{
    using (TripleDESCryptoServiceProvider tripleDESCryptoService = new TripleDESCryptoServiceProvider())
    {
        using (MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider())
        {
            byte[] byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
            tripleDESCryptoService.Key = byteHash;
            tripleDESCryptoService.Mode = CipherMode.ECB;//CBC, CFB
            byte[] data = Encoding.Unicode.GetBytes(source);
            return Convert.ToBase64String(tripleDESCryptoService.CreateEncryptor().TransformFinalBlock(data, 0, data.Length));
        }
    }
}

Similarly, Create a Decrypt method to decrypt your data using Triple DES algorithm.

public static string Decrypt(string encrypt, string key)
{
    using (TripleDESCryptoServiceProvider tripleDESCryptoService = new TripleDESCryptoServiceProvider())
    {
        using (MD5CryptoServiceProvider hashMD5Provider = new MD5CryptoServiceProvider())
        {
            byte[] byteHash = hashMD5Provider.ComputeHash(Encoding.UTF8.GetBytes(key));
            tripleDESCryptoService.Key = byteHash;
            tripleDESCryptoService.Mode = CipherMode.ECB;//CBC, CFB
            byte[] byteBuff = Convert.FromBase64String(encrypt);
            return Encoding.Unicode.GetString(tripleDESCryptoService.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
        }
    }
}

The Triple DES algorithm performs encryption and decryption in c# with key, so you need to enter the key when encrypting and decrypting the text using c# code.

Add code to the Encrypt button click event as the following c# code behind.

private void btnEncrypt_Click(object sender, EventArgs e)
{
    txtEncrypt.Text = Encrypt(txtInput.Text, txtKey.Text);
}

Finally, Add code to the Decrypt button click event to solve the triple des decryption c#.

private void btnDecrypt_Click(object sender, EventArgs e)
{
    txtDecrypt.Text = Decrypt(txtEncrypt.Text, txtKey.Text);
}

This example provides a basic implementation of Triple DES encryption and decryption in C# Windows Forms. You can also use the Triple DES algorithm to encrypt and decrypt password in c#.