3DES File Encryption (C#)

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

 https://en.wikipedia.org/w/index.php?title=Triple_DES&oldid=995820064

 To use 3DES functionality first off all we need to include “System.Security.Cryptography”.

using System.Security.Cryptography;  

Then we should create and adjust an object which will do encryption:

var tdese = TripleDES.Create();
tdese.Mode = CipherMode.ECB;
tdese.Padding = PaddingMode.PKCS7;
tdese.Key = ConvertHexStringToByteArray("AABBCCDDEE11223344556677889900FF");
var encryptor = tdese.CreateEncryptor(); 

“ConvertHexStringToByteArray” function to convert hex string to byte array:

public static byte[] ConvertHexStringToByteArray(string hexString)
{
          if (hexString.Length % 2 != 0)
          {
              throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "The binary key cannot have an odd number of digits: {0}", hexString));
          }
 
          byte[] HexAsBytes = new byte[hexString.Length / 2];
          for (int index = 0; index < HexAsBytes.Length; index++)
          {
              string byteValue = hexString.Substring(index * 2, 2);
 
              if (byteValue == "  ")
              {
                  HexAsBytes[index] = Convert.ToByte("32");
              }
              else
              {
                  HexAsBytes[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
              }
          }
 
          return HexAsBytes;
}

Source code below shows how to use object “encryptor” to encrypt the file “FileToEncrypt.txt”.

byte[] result = null;
byte[] data = File.ReadAllBytes("FileToEncrypt.txt");
using (var mse = new MemoryStream())
   {
      using (var cs = new CryptoStream(mse, encryptor, CryptoStreamMode.Write))
                            cs.Write(data, 0, data.Length);
 
      result = mse.ToArray();
   }
 
if (result != null)
   {
      string encrypteddata = UTF8Encoding.Default.GetString(result);
      File.AppendAllText("OutputFileName" + ".enc", encrypteddata, UTF8Encoding.Default);
   }

With this code we can store our file “FileToEncrypt.txt” encrypted as “OutputFileName.enc”. Decryption can be done with “tdese.CreateDecryptor();”.

More Information

Comments

Popular posts from this blog

Delta PLC Read/Write internal relay M in C#

Monitor Temperature, Humidity, Fire and Smoke of Room

File Privacy