Crypting data using 3des on c#

Today i have to use c# to crypt some data using 3des, so here is a pretty basic example to do it, i test it using mono.

  1.  
  2. using System;
  3. using System.Security.Cryptography; // used for TripleDESCryptoServiceProvider
  4. using System.Text; // used for Encoding.ASCII.GetBytes
  5.  
  6. public class Test
  7. {
  8.         static public void Main ()
  9.         {
  10.                 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider(); // i create the 3des object
  11.                 byte[] key = Encoding.ASCII.GetBytes("123456781234567812345678"); // the key should be 24 chars long
  12.                 string data = "Here goes the data to encrypt";
  13.                 des.Mode = CipherMode.CBC; // We’ll use CBC
  14.                 des.Key = key; // I set the key
  15.                 byte[] iv = des.IV; // I store the randomly generated IV since i will need for decrypt
  16.                 byte[] inputArray = UTF8Encoding.UTF8.GetBytes(data);
  17.                 ICryptoTransform cTransform = des.CreateEncryptor();
  18.                 byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
  19.                 // i will print as readble data
  20.                 Console.WriteLine( (Convert.ToBase64String(resultArray)) );
  21.                 Console.WriteLine( (Convert.ToBase64String(iv)) );
  22.         }
  23. }
  24.  
  25.  

One thought on “Crypting data using 3des on c#

Leave a Reply

Your email address will not be published. Required fields are marked *