Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement Triple DES in C# (complete example)

I want to use triple DES in C# for encryption/decryption of (utf8) strings with a (utf8) key of any length.

I am looking for these three functions

public static string Encrypt(string data, string key)
{
    ...
}

public static string Decrypt(string data, string key)
{
    ...
}

public static string GenerateKeyFromString(string str)
{
    ...
}

Note: Before anyone links to it, the http://www.geekzilla.co.uk/view7B360BD8-A77C-4F1F-BCA0-ACD0F6795F61.htm implementation does not work, I have thoroughly tested it.

I have done lots of searching and found bits of the problem like EncryptOneBlock and others but I am looking for a complete 'for dummies' implementation which I think would be useful for others too.

Thanks in advance!

like image 980
James Avatar asked Jul 10 '12 12:07

James


People also ask

What is 3 or Triple DES?

Triple Data Encryption Standard (DES) is a type of computerized cryptography where block cipher algorithms are applied three times to each data block. The key size is increased in Triple DES to ensure additional security through encryption capabilities. Each block contains 64 bits of data.

Is 3DES the same as Triple DES?

Both AES and 3DES, often known as triple-DES, are symmetric block ciphers. These are the current data encryption standards.

What is Triple DES key?

In cryptography, Triple DES (3DES or TDES), officially the Triple Data Encryption Algorithm (TDEA or Triple DEA), is a symmetric-key block cipher, which applies the DES cipher algorithm three times to each data block.


2 Answers

Complete source here: http://www.codeproject.com/Articles/14150/Encrypt-and-Decrypt-Data-with-C

Encrypt:

public static string Encrypt(string toEncrypt, bool useHashing)
{
    byte[] keyArray;
    byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();
    // Get the key from config file

    string key = (string)settingsReader.GetValue("SecurityKey", 
                                                     typeof(String));
    //System.Windows.Forms.MessageBox.Show(key);
    //If hashing use get hashcode regards to your key
    if (useHashing)
    {
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //Always release the resources and flush data
        // of the Cryptographic service provide. Best Practice

        hashmd5.Clear();
    }
    else
        keyArray = UTF8Encoding.UTF8.GetBytes(key);

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    //set the secret key for the tripleDES algorithm
    tdes.Key = keyArray;
    //mode of operation. there are other 4 modes.
    //We choose ECB(Electronic code Book)
    tdes.Mode = CipherMode.ECB;
    //padding mode(if any extra byte added)

    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateEncryptor();
    //transform the specified region of bytes array to resultArray
    byte[] resultArray = 
      cTransform.TransformFinalBlock(toEncryptArray, 0, 
      toEncryptArray.Length);
    //Release resources held by TripleDes Encryptor
    tdes.Clear();
    //Return the encrypted data into unreadable string format
    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}

Decrypt:

public static string Decrypt(string cipherString, bool useHashing)
{
    byte[] keyArray;
    //get the byte code of the string

    byte[] toEncryptArray = Convert.FromBase64String(cipherString);

    System.Configuration.AppSettingsReader settingsReader = 
                                        new AppSettingsReader();
    //Get your key from config file to open the lock!
    string key = (string)settingsReader.GetValue("SecurityKey", 
                                                 typeof(String));
            
    if (useHashing)
    {
        //if hashing was used get the hash code with regards to your key
        MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
        keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
        //release any resource held by the MD5CryptoServiceProvider

        hashmd5.Clear();
    }
    else
    {
        //if hashing was not implemented get the byte code of the key
        keyArray = UTF8Encoding.UTF8.GetBytes(key);
    }

    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
    //set the secret key for the tripleDES algorithm
    tdes.Key = keyArray;
    //mode of operation. there are other 4 modes. 
    //We choose ECB(Electronic code Book)

    tdes.Mode = CipherMode.ECB;
    //padding mode(if any extra byte added)
    tdes.Padding = PaddingMode.PKCS7;

    ICryptoTransform cTransform = tdes.CreateDecryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(
                         toDecryptArray, 0, toDecryptArray.Length);
    //Release resources held by TripleDes Encryptor                
    tdes.Clear();
    //return the Clear decrypted TEXT
    return UTF8Encoding.UTF8.GetString(resultArray);
}
like image 113
Chris Gessler Avatar answered Sep 17 '22 17:09

Chris Gessler


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

public class TripleDESImp
{
    public static readonly string Key = ConfigurationManager.AppSettings["Encryption_Key"];
    public static readonly Encoding Encoder = Encoding.UTF8;

    public static string TripleDesEncrypt(string plainText)
    {
        var des = CreateDes(Key);
        var ct = des.CreateEncryptor();
        var input = Encoding.UTF8.GetBytes(plainText);
        var output = ct.TransformFinalBlock(input, 0, input.Length);
        return Convert.ToBase64String(output);
    }

    public static string TripleDesDecrypt(string cypherText)
    {
        var des = CreateDes(Key);
        var ct = des.CreateDecryptor();
        var input = Convert.FromBase64String(cypherText);
        var output = ct.TransformFinalBlock(input, 0, input.Length);
        return Encoding.UTF8.GetString(output);
    }

    public static TripleDES CreateDes(string key)
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        TripleDES des = new TripleDESCryptoServiceProvider();
        var desKey= md5.ComputeHash(Encoding.UTF8.GetBytes(key));
        des.Key = desKey;
        des.IV = new byte[des.BlockSize / 8];
        des.Padding=PaddingMode.PKCS7;
        des.Mode=CipherMode.ECB;
        return des;
    }
}

<configuration>
<appsettings>
<add key="Encryption_Key" value="put_your_encryption_key_here"/>
</appsettings>
<configuration>
like image 34
Godwin Awojobi Avatar answered Sep 17 '22 17:09

Godwin Awojobi