Back to all posts
C#.NETSecurity

How to TripleDES Encrypt Decrypt Data? – Part Two

SathishApril 23, 2010
How to TripleDES Encrypt Decrypt Data? – Part Two

This is the continuation of Part One of the TripleDES encryption tutorial.

Decryption Implementation

csharp
public static string Decrypt(string cipherText, string key)
{
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    
    using (TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider())
    {
        tdes.Key = Encoding.UTF8.GetBytes(key.Substring(0, 24));
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;
        
        ICryptoTransform decryptor = tdes.CreateDecryptor();
        byte[] decryptedBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
        
        return Encoding.UTF8.GetString(decryptedBytes);
    }
}

Complete Example

csharp
class Program
{
    static void Main(string[] args)
    {
        string key = "123456789012345678901234"; // 24 characters for TripleDES
        string originalText = "Hello, World!";
        
        string encrypted = Encrypt(originalText, key);
        Console.WriteLine("Encrypted: " + encrypted);
        
        string decrypted = Decrypt(encrypted, key);
        Console.WriteLine("Decrypted: " + decrypted);
    }
}

Remember to always use secure key management practices in production environments.

0claps
Share this post

Comments

Protected by reCAPTCHA v3

No comments yet. Be the first to comment.