473,320 Members | 2,164 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

criptografy 3DES

How can i encode (binary) file, eg PDF or txt , with 3DES in C#?
May 16 '07 #1
2 2217
Motoma
3,237 Expert 2GB
The System.Security.Cryptography namespace provides a DES class for performing DES based encryption and decryption.
May 17 '07 #2
TRScheel
638 Expert 512MB
How can i encode (binary) file, eg PDF or txt , with 3DES in C#?

Here is a simple program to encrypt text using the TripleDES method.

To have it do a .PDF read it in byte by byte, and change the encryption method to pass in a byte array, and write that. To have it do a .TXT, read in the file using StreamReader and pass the ReadToEnd() result to the encryption method.

Everything should be fairly self documenting, except where noted.

Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Security.Cryptography;
  5. using System.IO;
  6.  
  7. namespace CryptoTest
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             TripleDES tripleDes;
  14.             string filelocation;
  15.             string textToFile;
  16.             string decryptedText;
  17.             byte[] encryptedText;
  18.  
  19.             InitializeStrings(out filelocation, out textToFile);
  20.  
  21.             tripleDes = InitializeTripleDES();
  22.  
  23.             encryptedText = EncryptMessage(textToFile, tripleDes);
  24.             Console.WriteLine("Encryption attempt done");
  25.             PressAnyKeyToContinue();
  26.  
  27.             WriteStringToFile(filelocation, ByteArrayToString(encryptedText));
  28.  
  29.             encryptedText = ReadByteArrayFromFile(filelocation);
  30.             decryptedText = DecryptMessage(encryptedText, tripleDes);
  31.  
  32.             Console.WriteLine(string.IsNullOrEmpty(decryptedText) ? "Previous error left no message to decrypt" : 
  33.                 string.Format("\nDecrypted Message:\n\n{0}", decryptedText));
  34.             PressAnyKeyToContinue();            
  35.         }
  36.  
  37.         private static TripleDES InitializeTripleDES()
  38.         {
  39.             TripleDES tripleDes;
  40.             tripleDes = TripleDES.Create();
  41.             tripleDes.GenerateIV();
  42.             tripleDes.GenerateKey();
  43.  
  44.             /* NOTE: You will want to save the Key and IV somewhere if you want to unencrypt these files at a later date.
  45.              * With that thought in mind, remember that computer security is only as strong as its users, ie... keep
  46.              * the IV and Key in a secure location */
  47.  
  48.             Console.WriteLine("Triple DES initialized");
  49.  
  50.             Console.Write("\tKey: ");
  51.             Console.Write(ByteArrayToString(tripleDes.Key));
  52.             Console.Write("\n");
  53.  
  54.             Console.Write("\tIV: ");
  55.             Console.Write(ByteArrayToString(tripleDes.IV));
  56.             Console.Write("\n");
  57.  
  58.             PressAnyKeyToContinue();
  59.             return tripleDes;
  60.         }
  61.  
  62.         private static string ByteArrayToString(byte[] byteArray)
  63.         {
  64.             string result = string.Empty;
  65.  
  66.             if (byteArray == null)
  67.                 return result;
  68.  
  69.             for (int i = 0; i < byteArray.Length; i++)
  70.             {
  71.                 if (i != 0)
  72.                     result += string.Format("-{0}", byteArray[i]);
  73.                 else
  74.                     result += string.Format("{0}", byteArray[i]);
  75.             }
  76.  
  77.             /*I have found that writing the byte array out in this form makes it easier to extract later on, because if we use
  78.              System.Text.Encoding.ASCIIEncoding.GetString() we will lose some of the information. Convert to 64 bit string
  79.              also seems to have issues too.*/
  80.  
  81.             return result;
  82.         }
  83.  
  84.         private static byte[] StringToByteArray(string text, char seperator)
  85.         {
  86.             string[] splitText;
  87.             List<byte> result;
  88.  
  89.             result = new List<byte>();
  90.             splitText = text.Split(seperator);
  91.  
  92.             for (int i = 0; i < splitText.Length; i++)
  93.             {
  94.                 result.Add(byte.Parse(splitText[i]));
  95.             }
  96.  
  97.             return result.ToArray();
  98.         }
  99.  
  100.         private static void PressAnyKeyToContinue()
  101.         {
  102.             Console.WriteLine();
  103.             Console.WriteLine("Press any key to continue");
  104.             Console.ReadKey(true);
  105.         }
  106.  
  107.         private static void InitializeStrings(out string filelocation, out string textToFile)
  108.         {
  109.             filelocation = "test.txt";
  110.             textToFile = "This is a test\n" + "We will be testing the triple DES encryption/decryption\n" +
  111.                 "And ensuring we understand how to use it";
  112.  
  113.             Console.WriteLine("Location: {0}", filelocation);
  114.             Console.WriteLine("Text To Write: \n{0}", textToFile);
  115.  
  116.             PressAnyKeyToContinue();
  117.         }
  118.  
  119.         private static byte[] ReadByteArrayFromFile(string fileLocation)
  120.         {
  121.             byte[] byteArray = null;
  122.             StreamReader SReader = null;
  123.  
  124.             Console.WriteLine("Beginning reading byte array from file...");
  125.             if (string.IsNullOrEmpty(fileLocation))
  126.             {
  127.                 Console.WriteLine("\t Error: File location is null or empty");
  128.                 return null;
  129.             }
  130.  
  131.             try
  132.             {
  133.                 SReader = new StreamReader(fileLocation);
  134.                 Console.WriteLine("\t Stream reader created");
  135.                 byteArray = StringToByteArray(SReader.ReadToEnd(), '-');
  136.                 Console.WriteLine("Byte array successfully extracted");
  137.             }
  138.             catch (Exception e)
  139.             {
  140.                 Console.WriteLine(e.Message);
  141.                 Console.WriteLine("Error reading contents of file: {0}", fileLocation);
  142.             }
  143.             finally
  144.             {
  145.                 if (SReader != null)
  146.                     SReader.Close();
  147.             }
  148.  
  149.             PressAnyKeyToContinue();
  150.             return byteArray;
  151.         }
  152.  
  153.         private static void WriteStringToFile(string fileLocation, string text)
  154.         {
  155.             StreamWriter SWriter = null;
  156.  
  157.             Console.WriteLine("Beginning write to file...");
  158.             if (string.IsNullOrEmpty(fileLocation))
  159.             {
  160.                 Console.WriteLine("\t Error: File location is null or empty");
  161.                 return;
  162.             }
  163.             else if (string.IsNullOrEmpty(text))
  164.             {
  165.                 Console.WriteLine("\t Error: Text to write is null or empty");
  166.                 return;
  167.             }
  168.  
  169.  
  170.             try
  171.             {
  172.                 SWriter = new StreamWriter(fileLocation);
  173.                 Console.WriteLine("\t Stream writer created");
  174.                 SWriter.Write(text);
  175.                 Console.WriteLine("Text written successfully");
  176.             }
  177.             catch (Exception e)
  178.             {
  179.                 Console.WriteLine(e.Message);
  180.                 Console.WriteLine("Error writing text:\n\n{0}\n\n to file: {1}", text, fileLocation);
  181.             }
  182.             finally
  183.             {
  184.                 if (SWriter != null)
  185.                     SWriter.Close();
  186.             }
  187.  
  188.             PressAnyKeyToContinue();
  189.         }
  190.  
  191.         private static byte[] EncryptMessage(string text, TripleDES tripleDes)
  192.         {
  193.             MemoryStream MemStream = null;
  194.             CryptoStream CStream = null;
  195.             StreamWriter SWriter = null;
  196.  
  197.             Console.WriteLine("Beginning encryption...");
  198.             if (string.IsNullOrEmpty(text))
  199.             {
  200.                 Console.WriteLine("\t Error: Text to encrypt is null or empty");
  201.                 return null;
  202.             }
  203.             else if (tripleDes == null)
  204.             {
  205.                 Console.WriteLine("\t Error: Triple DES object is null");
  206.                 return null;
  207.             }
  208.  
  209.             try
  210.             {
  211.                 MemStream = new MemoryStream();
  212.                 Console.WriteLine("\t Memory stream created");
  213.                 CStream = new CryptoStream(MemStream, tripleDes.CreateEncryptor(), CryptoStreamMode.Write);
  214.                 Console.WriteLine("\t Crypto stream created");
  215.                 SWriter = new StreamWriter(CStream);
  216.                 Console.WriteLine("\t Stream writer created");
  217.                 SWriter.Write(text);
  218.                 SWriter.Flush();
  219.                 CStream.FlushFinalBlock();
  220.                 Console.WriteLine("\t Text wrote to stream");
  221.                 return MemStream.ToArray();
  222.             }
  223.             catch (Exception e)
  224.             {
  225.                 Console.WriteLine(e.Message);
  226.                 Console.WriteLine("Error encrypting text: {0}", text);
  227.             }
  228.             finally
  229.             {
  230.                 if (SWriter != null)
  231.                     SWriter.Close();
  232.  
  233.                 if (CStream != null)
  234.                     CStream.Close();
  235.  
  236.                 if (MemStream != null)
  237.                     MemStream.Close();
  238.             }
  239.  
  240.             return null;
  241.         }
  242.  
  243.         private static string DecryptMessage(byte[] encryptedText, TripleDES tripleDes)
  244.         {
  245.             MemoryStream MemStream = null;
  246.             CryptoStream CStream = null;
  247.             StreamReader SReader = null;
  248.  
  249.             Console.WriteLine("Beginning message decryption...");
  250.             if (encryptedText == null)
  251.             {
  252.                 Console.WriteLine("\t Error: Byte array to decrypt is null");
  253.                 return null;
  254.             }
  255.             else if (tripleDes == null)
  256.             {
  257.                 Console.WriteLine("\t Error: Triple DES object is null");
  258.                 return null;
  259.             }
  260.  
  261.             try
  262.             {
  263.                 MemStream = new MemoryStream(encryptedText);
  264.                 Console.WriteLine("\t Memory stream created");
  265.                 CStream = new CryptoStream(MemStream, tripleDes.CreateDecryptor(), CryptoStreamMode.Read);
  266.                 Console.WriteLine("\t Crypto stream created");
  267.                 SReader = new StreamReader(CStream);
  268.                 Console.WriteLine("\t Stream reader created");
  269.                 return SReader.ReadToEnd();
  270.             }
  271.             catch(Exception e)
  272.             {
  273.                 Console.WriteLine(e.Message);
  274.                 Console.WriteLine("Error decrypting bytes: {0}", ByteArrayToString(encryptedText));
  275.             }
  276.             finally
  277.             {
  278.                 try
  279.                 {
  280.                     if (CStream != null)
  281.                         CStream.Close();
  282.  
  283.                     if (MemStream != null)
  284.                         MemStream.Close();
  285.  
  286.                     if (SReader != null)
  287.                         SReader.Close();
  288.                 }
  289.                 catch
  290.                 { }
  291.             }
  292.  
  293.             return string.Empty;
  294.         }
  295.     }
  296. }
May 17 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: underwmd | last post by:
Hello, My problem is two fold. 1) I must support a deployed legacy application written in VB6 SP5. I need to export data from a database, compress it and the encrypt the data using 3DES (to...
3
by: Simang | last post by:
Hi, I am trying to encrypt viewstate in my ASP.NET web site. I put these items in the web.config.. <pages enableViewStateMac="true" /> <machineKey validation="3DES"/> However, when I tried...
0
by: Frederic ESNOUF \(MVP-ISA\) | last post by:
Hi, My question is about 3des, ... in fact the difference between 3DES with Capicom (VB) and VB.net With VB6/capicom, encrypting data is simple : message.Content = "This is my bank account :...
0
by: tshad | last post by:
I have been trying to create encoding/decoding functions for secure Credit Card information. I was looking at 3DES/MD5 and RC2/MD5. I found a simple function that seemed to work pretty well,...
1
by: Sathyaish | last post by:
I have the following scenario: Algorithm: 3DES Cipher Mode: CBC Key Size: 128-bit Block Size: 64 bit IV: 0x0000000000000000 (an eight byte array of zeros) The results I get using .NET with...
1
by: tshad | last post by:
I am trying to use 3DES to encrypt my keys and am using VS 2003. I am confused with some code I have that seems to use a hash (MD5) in the 3DES. But a Hash is one way. You are not suppose to be...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.