How can i encode (binary) file, eg PDF or txt , with 3DES in C#?
2 2217
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. - using System;
-
using System.Collections.Generic;
-
using System.Text;
-
using System.Security.Cryptography;
-
using System.IO;
-
-
namespace CryptoTest
-
{
-
class Program
-
{
-
static void Main(string[] args)
-
{
-
TripleDES tripleDes;
-
string filelocation;
-
string textToFile;
-
string decryptedText;
-
byte[] encryptedText;
-
-
InitializeStrings(out filelocation, out textToFile);
-
-
tripleDes = InitializeTripleDES();
-
-
encryptedText = EncryptMessage(textToFile, tripleDes);
-
Console.WriteLine("Encryption attempt done");
-
PressAnyKeyToContinue();
-
-
WriteStringToFile(filelocation, ByteArrayToString(encryptedText));
-
-
encryptedText = ReadByteArrayFromFile(filelocation);
-
decryptedText = DecryptMessage(encryptedText, tripleDes);
-
-
Console.WriteLine(string.IsNullOrEmpty(decryptedText) ? "Previous error left no message to decrypt" :
-
string.Format("\nDecrypted Message:\n\n{0}", decryptedText));
-
PressAnyKeyToContinue();
-
}
-
-
private static TripleDES InitializeTripleDES()
-
{
-
TripleDES tripleDes;
-
tripleDes = TripleDES.Create();
-
tripleDes.GenerateIV();
-
tripleDes.GenerateKey();
-
-
/* NOTE: You will want to save the Key and IV somewhere if you want to unencrypt these files at a later date.
-
* With that thought in mind, remember that computer security is only as strong as its users, ie... keep
-
* the IV and Key in a secure location */
-
-
Console.WriteLine("Triple DES initialized");
-
-
Console.Write("\tKey: ");
-
Console.Write(ByteArrayToString(tripleDes.Key));
-
Console.Write("\n");
-
-
Console.Write("\tIV: ");
-
Console.Write(ByteArrayToString(tripleDes.IV));
-
Console.Write("\n");
-
-
PressAnyKeyToContinue();
-
return tripleDes;
-
}
-
-
private static string ByteArrayToString(byte[] byteArray)
-
{
-
string result = string.Empty;
-
-
if (byteArray == null)
-
return result;
-
-
for (int i = 0; i < byteArray.Length; i++)
-
{
-
if (i != 0)
-
result += string.Format("-{0}", byteArray[i]);
-
else
-
result += string.Format("{0}", byteArray[i]);
-
}
-
-
/*I have found that writing the byte array out in this form makes it easier to extract later on, because if we use
-
System.Text.Encoding.ASCIIEncoding.GetString() we will lose some of the information. Convert to 64 bit string
-
also seems to have issues too.*/
-
-
return result;
-
}
-
-
private static byte[] StringToByteArray(string text, char seperator)
-
{
-
string[] splitText;
-
List<byte> result;
-
-
result = new List<byte>();
-
splitText = text.Split(seperator);
-
-
for (int i = 0; i < splitText.Length; i++)
-
{
-
result.Add(byte.Parse(splitText[i]));
-
}
-
-
return result.ToArray();
-
}
-
-
private static void PressAnyKeyToContinue()
-
{
-
Console.WriteLine();
-
Console.WriteLine("Press any key to continue");
-
Console.ReadKey(true);
-
}
-
-
private static void InitializeStrings(out string filelocation, out string textToFile)
-
{
-
filelocation = "test.txt";
-
textToFile = "This is a test\n" + "We will be testing the triple DES encryption/decryption\n" +
-
"And ensuring we understand how to use it";
-
-
Console.WriteLine("Location: {0}", filelocation);
-
Console.WriteLine("Text To Write: \n{0}", textToFile);
-
-
PressAnyKeyToContinue();
-
}
-
-
private static byte[] ReadByteArrayFromFile(string fileLocation)
-
{
-
byte[] byteArray = null;
-
StreamReader SReader = null;
-
-
Console.WriteLine("Beginning reading byte array from file...");
-
if (string.IsNullOrEmpty(fileLocation))
-
{
-
Console.WriteLine("\t Error: File location is null or empty");
-
return null;
-
}
-
-
try
-
{
-
SReader = new StreamReader(fileLocation);
-
Console.WriteLine("\t Stream reader created");
-
byteArray = StringToByteArray(SReader.ReadToEnd(), '-');
-
Console.WriteLine("Byte array successfully extracted");
-
}
-
catch (Exception e)
-
{
-
Console.WriteLine(e.Message);
-
Console.WriteLine("Error reading contents of file: {0}", fileLocation);
-
}
-
finally
-
{
-
if (SReader != null)
-
SReader.Close();
-
}
-
-
PressAnyKeyToContinue();
-
return byteArray;
-
}
-
-
private static void WriteStringToFile(string fileLocation, string text)
-
{
-
StreamWriter SWriter = null;
-
-
Console.WriteLine("Beginning write to file...");
-
if (string.IsNullOrEmpty(fileLocation))
-
{
-
Console.WriteLine("\t Error: File location is null or empty");
-
return;
-
}
-
else if (string.IsNullOrEmpty(text))
-
{
-
Console.WriteLine("\t Error: Text to write is null or empty");
-
return;
-
}
-
-
-
try
-
{
-
SWriter = new StreamWriter(fileLocation);
-
Console.WriteLine("\t Stream writer created");
-
SWriter.Write(text);
-
Console.WriteLine("Text written successfully");
-
}
-
catch (Exception e)
-
{
-
Console.WriteLine(e.Message);
-
Console.WriteLine("Error writing text:\n\n{0}\n\n to file: {1}", text, fileLocation);
-
}
-
finally
-
{
-
if (SWriter != null)
-
SWriter.Close();
-
}
-
-
PressAnyKeyToContinue();
-
}
-
-
private static byte[] EncryptMessage(string text, TripleDES tripleDes)
-
{
-
MemoryStream MemStream = null;
-
CryptoStream CStream = null;
-
StreamWriter SWriter = null;
-
-
Console.WriteLine("Beginning encryption...");
-
if (string.IsNullOrEmpty(text))
-
{
-
Console.WriteLine("\t Error: Text to encrypt is null or empty");
-
return null;
-
}
-
else if (tripleDes == null)
-
{
-
Console.WriteLine("\t Error: Triple DES object is null");
-
return null;
-
}
-
-
try
-
{
-
MemStream = new MemoryStream();
-
Console.WriteLine("\t Memory stream created");
-
CStream = new CryptoStream(MemStream, tripleDes.CreateEncryptor(), CryptoStreamMode.Write);
-
Console.WriteLine("\t Crypto stream created");
-
SWriter = new StreamWriter(CStream);
-
Console.WriteLine("\t Stream writer created");
-
SWriter.Write(text);
-
SWriter.Flush();
-
CStream.FlushFinalBlock();
-
Console.WriteLine("\t Text wrote to stream");
-
return MemStream.ToArray();
-
}
-
catch (Exception e)
-
{
-
Console.WriteLine(e.Message);
-
Console.WriteLine("Error encrypting text: {0}", text);
-
}
-
finally
-
{
-
if (SWriter != null)
-
SWriter.Close();
-
-
if (CStream != null)
-
CStream.Close();
-
-
if (MemStream != null)
-
MemStream.Close();
-
}
-
-
return null;
-
}
-
-
private static string DecryptMessage(byte[] encryptedText, TripleDES tripleDes)
-
{
-
MemoryStream MemStream = null;
-
CryptoStream CStream = null;
-
StreamReader SReader = null;
-
-
Console.WriteLine("Beginning message decryption...");
-
if (encryptedText == null)
-
{
-
Console.WriteLine("\t Error: Byte array to decrypt is null");
-
return null;
-
}
-
else if (tripleDes == null)
-
{
-
Console.WriteLine("\t Error: Triple DES object is null");
-
return null;
-
}
-
-
try
-
{
-
MemStream = new MemoryStream(encryptedText);
-
Console.WriteLine("\t Memory stream created");
-
CStream = new CryptoStream(MemStream, tripleDes.CreateDecryptor(), CryptoStreamMode.Read);
-
Console.WriteLine("\t Crypto stream created");
-
SReader = new StreamReader(CStream);
-
Console.WriteLine("\t Stream reader created");
-
return SReader.ReadToEnd();
-
}
-
catch(Exception e)
-
{
-
Console.WriteLine(e.Message);
-
Console.WriteLine("Error decrypting bytes: {0}", ByteArrayToString(encryptedText));
-
}
-
finally
-
{
-
try
-
{
-
if (CStream != null)
-
CStream.Close();
-
-
if (MemStream != null)
-
MemStream.Close();
-
-
if (SReader != null)
-
SReader.Close();
-
}
-
catch
-
{ }
-
}
-
-
return string.Empty;
-
}
-
}
-
}
Sign in to post your reply or Sign up for a free account.
Similar topics
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...
|
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...
|
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 :...
|
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,...
|
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...
|
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...
|
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...
|
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...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
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...
|
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...
|
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...
|
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)...
|
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
|
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...
| |