I have an interesting deli ma on my hands. I have created a program that takes 1-∞ zipped files that also contain X amount of individual files. The files in different folders sometimes get the same file name for whatever reason. This is my code that I have so far...
What this piece of code does is that after the object that is instantiated another object calls this function called unzip(). what all failsafe.check_directory() just makes sure that the temporary folder were all the going to be unzipped files are going to go in is empty. the first try catch is for anything I do not know about yet, but the second try catch is for catching duplicate duplicate files so when it actually does happen... the program will not break. So the question I am Asking is what is the best way to handle this exception without just kicking the duplicate to the side or in other words, is there to rename that file before its to late.
public bool unzip()
{
int bad_file = 0;
failsafe.check_directory();
string dupes = "dupe files\r\n";
try
{
for (int i = 0; i < zippedfolders.Length; i++)
{
try
{
bad_file = i;
ZipFile.ExtractToDirectory(zippedfolders[i], temppath);
}
catch
{
dupes += zippedfolders[bad_file]+"\r\n";
continue;
}
}
File.WriteAllText(#"C:\MDSSCRUBBER\BUGGED_FILE.txt", dupes);
files = Directory.GetFiles(temppath);
return true;
}
catch
{
return false;
}
}
This is how I handled it... For some odd reason the Directory class is not creating a folder in the Desktop.
private void fix_desktop()
{
string pathington = Environment.SpecialFolder.Desktop + #"\MrEncrypto\";
bool check = !Directory.Exists(pathington);
string finaloutput = Environment.SpecialFolder.Desktop + #"\MrEncrypto\";
if (!check)
{
Directory.CreateDirectory(pathington);
}
else
{
foreach (string file in Directory.GetFiles(Environment.SpecialFolder.Desktop + #"\MrEncrypto"))
{
File.Delete(file);
}
}
foreach (string file in files)
{
try
{
FileStream fsInput = new FileStream(file, FileMode.Open, FileAccess.Read);
FileStream fsencrypt = new FileStream(finaloutput + Path.GetFileName(file), FileMode.Create, FileAccess.Write);
/** DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
DES.IV = ASCIIEncoding.ASCII.GetBytes(IV);**/
AesCryptoServiceProvider DES = new AesCryptoServiceProvider();
DES.BlockSize = 128;
DES.KeySize = 256;
DES.IV = ASCIIEncoding.ASCII.GetBytes(IV);
DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
DES.Padding = PaddingMode.PKCS7;
DES.Mode = CipherMode.CBC;
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream ocstream = new CryptoStream(fsencrypt, desencrypt, CryptoStreamMode.Write);
//reading time
byte[] filetobyte = new byte[fsInput.Length - 1];
fsInput.Read(filetobyte, 0, filetobyte.Length);
ocstream.Write(filetobyte, 0, filetobyte.Length);
fsInput.Close();
ocstream.Close();
fsencrypt.Close();
}
catch
{
continue;
}
}//foreach
SystemSounds.Beep.Play();
Encrypto.Enabled = false;
}//function
Related
I have this applcation where it makes it easier for me when I screenshot and I need to send the screenshot to a friend/family and I wanted to take it to the next level where I encrypt the image before it saves.
The issue is that when I try it this way, it cuts the stream because it says that its being used in another process.
Did I make it flow the wrong way? Do I need to multi-thread?
Which method would be best for this, Await & Async?
public string generateKey()
{
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
private void saveScreenshot()
{
string path;
path = "%AppData%\\Image.png"; // collection of paths
path = Environment.ExpandEnvironmentVariables(path);
if (Clipboard.ContainsImage() == true)
{
Image image = (Image)Clipboard.GetDataObject().GetData(DataFormats.Bitmap);
image.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
}
else
{
}
}
private void encryptImage()
{
try
{
string path;
path = "%AppData%\\Image.png"; // collection of paths
path = Environment.ExpandEnvironmentVariables(path);
encrypt(path, path, key);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
//--------------------File Encryptor--------------------
private void encrypt(string input, string output, string strhash)
{
FileStream inFs, outFs;
CryptoStream cs;
TripleDESCryptoServiceProvider TDC = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteTexto;
inFs = new FileStream(input, FileMode.Open, FileAccess.Read);
outFs = new FileStream(output, FileMode.OpenOrCreate, FileAccess.Write);
byteHash = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strhash));
byteTexto = File.ReadAllBytes(input);
md5.Clear();
TDC.Key = byteHash;
TDC.Mode = CipherMode.ECB;
cs = new CryptoStream(outFs, TDC.CreateEncryptor(), CryptoStreamMode.Write);
int byteRead;
long length, position = 0;
length = inFs.Length;
while (position < length)
{
byteRead = inFs.Read(byteTexto, 0, byteTexto.Length);
position += byteRead;
cs.Write(byteTexto, 0, byteRead);
}
inFs.Close();
outFs.Close();
}
//--------------------File Encryptor--------------------
private void screenshot()
{
System.Windows.Forms.SendKeys.SendWait("{PRTSC}");
}
I am trying to multithread AES in C# but I can't seem to fix this weird exception. My buffer sizes are exactly the same but it still says it can't expand maybe you can see the error this is for a file of size 101 bytes.
In the while loop it will skip if and go inside the else creating (one thread?) that writes a not encrypted buffer to an encrypted buffer. After that is done to synchronize I want to write the encrypted buffer to a file in the runworkerComplete function. The issue presents itself when I try to write the not encrypted buffer into a encrypted buffer. The error message puzzles me since the size of the second buffer is created with the length of the first buffer but yet is says it can't expand the memory!?
static List<BackgroundWorker> threadCompany = new List<BackgroundWorker>();
static List<BackgroundWorker> listWorkers = new List<BackgroundWorker>();
static List<BackgroundWorker> listFreeWorkers = new List<BackgroundWorker>();
static FileStream fsIn;
static string file;
static byte[] key;
const int BLOCK_SIZE = 1000;
static FileStream outFile;
public static void EncryptFile(string inputFile, string outputFile, string sKey, ProgressBar progress)
{
String fileName = inputFile;
fileName = "\\" + fileName.Split('\\').Last();
var progres = new Progress<int>(value => progress.Value = value);
file = outputFile + fileName;
fsIn = new FileStream(inputFile, FileMode.Open);
outFile = new FileStream(file, FileMode.Create);
key = new UnicodeEncoding().GetBytes(sKey);
for (int t = 0; t < 4; t++)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
listWorkers.Add(worker);
listFreeWorkers.Add(worker);
}
byte[] buffer = new byte[BLOCK_SIZE];
FileInfo fileInfo = new FileInfo(inputFile);
double numBlocks = Math.Ceiling(((double)fileInfo.Length) / BLOCK_SIZE);
int ixCurrentBlock = 0;
while (ixCurrentBlock < numBlocks)
{
//check if any free workers
if (listFreeWorkers.Count > 0)
{
//Get the worker, remove it from the list
BackgroundWorker freeWorker = listFreeWorkers[0];
listFreeWorkers.RemoveAt(0);
//read the next block of the file
int bytes;
if (ixCurrentBlock < numBlocks - 1)
{
bytes = fsIn.Read(buffer, ixCurrentBlock * BLOCK_SIZE, BLOCK_SIZE);
freeWorker.RunWorkerAsync(Tuple.Create(ixCurrentBlock, buffer));
threadCompany.Remove(freeWorker);
}
else //special handling for last block
{
MessageBox.Show((ixCurrentBlock * BLOCK_SIZE) + " " + (int)(fileInfo.Length - ixCurrentBlock * BLOCK_SIZE)); // 0 101
bytes = fsIn.Read(buffer, ixCurrentBlock * BLOCK_SIZE, (int)(fileInfo.Length - ixCurrentBlock * BLOCK_SIZE));
freeWorker.RunWorkerAsync(Tuple.Create(ixCurrentBlock, new byte[(int)(fileInfo.Length - ixCurrentBlock * BLOCK_SIZE)]));
threadCompany.Remove(freeWorker);
}
//now pass it to a worker
//advance to the next block
ixCurrentBlock++;
//update the UI status here
// ...
}
else //no workers free
{
Thread.Sleep(50);
}
}
//if we make it to here we have sent off all the blocks
//now we wait for the threads to complete
bool threadsRunning = false;
while (threadsRunning)
{
threadsRunning = false;
foreach (BackgroundWorker worker in listWorkers)
{
threadsRunning |= worker.IsBusy;
}
//if still running, wait and try again in 50ms
if (threadsRunning)
{
Thread.Sleep(50);
}
}
}
private static void worker_DoWork(object sender, DoWorkEventArgs e)
{
Tuple<int, byte[]> t = e.Argument as Tuple<int, byte[]>;
int blockIndex = (int)t.Item1;
byte[] inBuffer = (byte[])t.Item2;
byte[] outBuffer = new byte[inBuffer.Length];
//using keyword will automatically close the stream
using (MemoryStream outStream = new MemoryStream(outBuffer)) // issue may be here?
{
RijndaelManaged RMCrypto = new RijndaelManaged();
using (CryptoStream cs = new CryptoStream(outStream,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write))
{
// I want to write inbuffer non encrypted to outbuffer encrypted.
cs.Write(inBuffer, blockIndex, inBuffer.Length);
}
}
e.Result = Tuple.Create(blockIndex, outBuffer);
}
private static void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show(e.Error.Message + " "); // memory is not expendable
Tuple<int, byte[]> t = e.Result as Tuple<int, byte[]>;
int blockIndex = (int)t.Item1;
byte[] buffer = (byte[])t.Item2;
//assumes you have a class variable, _outFile, that is an open filestream
outFile.Write(buffer, blockIndex, buffer.Length);
outFile.Close();
//add the worker back to the free workers list
listFreeWorkers.Add((BackgroundWorker)sender);
}
Encryption and decryption arn't the same size to solve this issue flush the stream (already implied with the using statement) toarray the stream to your outbuffer.
SOLUTION
private static void worker_DoWork(object sender, DoWorkEventArgs e)
{
Tuple<int, byte[]> t = e.Argument as Tuple<int, byte[]>;
int blockIndex = (int)t.Item1;
byte[] inBuffer = (byte[])t.Item2;
byte[] outBuffer;
//using keyword will automatically close the stream
using (MemoryStream outStream = new MemoryStream()) // issue may be here?
{
AesCryptoServiceProvider RMCrypto = new AesCryptoServiceProvider();
using (CryptoStream cs = new CryptoStream(outStream,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write))
{
// I want to write inbuffer non encrypted to outbuffer encrypted.
cs.Write(inBuffer, blockIndex, inBuffer.Length);
}
outBuffer = outStream.ToArray();
}
e.Result = Tuple.Create(blockIndex, outBuffer);
}
I am encrypting some text files. It works fine the file is encypted, however on occasion I get this error when attempting to delete the original unencrypted file:
System.IO.IOException:
The process cannot access the file 'MyFile.TXT' because it is being used by another process. at System.IO.__Error.WinIOError(Int32
errorCode, String maybeFullPath) at System.IO.File.Delete(String
path) at FileEncryption.Program.DeleteFile(String sInputFilename) in
FileEncryption\Program.cs:line 159
This seems to happen on large text files. (50MB+) but not always.
Any idea what I might be doing wrong?
Method to PROCESS the folder of txt files:
private static void BeginFileProcessing(string sSecretKey_)
{
DirectoryInfo di = new DirectoryInfo(_sourcePath);
FileInfo[] files = di.GetFiles(_fileType);
try
{
foreach (FileInfo file in files)
{
string thisFileExt = Path.GetExtension(file.Name);
string thisFileName = Path.GetFileNameWithoutExtension(file.Name);
string encFileName = String.Format("{0}-enc{1}", thisFileName, thisFileExt);
if (_TestingOnly)
{
Console.Write("Source: " + file.Name + " " +
" Encrypted File: " + encFileName + "\n");
}
EncryptFile(file.FullName, _targetPath + encFileName, sSecretKey_);
if (_DeleteOriginal)
{
Console.WriteLine("Deleteing file: " + file.FullName);
DeleteFile(file.FullName);
}
}
}
catch (Exception ex)
{
LogWriter(string.Format("\nError Decrypting file: {0}", ex), true);
}
}
Method to ENCRYPT the files
private static void EncryptFile(string sInputFilename,
string sOutputFilename, string sKey)
{
FileStream fsInput =
new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted =
new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream =
new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);
try
{
byte[] bytearrayinput = System.IO.File.ReadAllBytes(sInputFilename);
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}
catch (Exception ex)
{
string error = "";
foreach (DictionaryEntry pair in ex.Data)
{
error += pair.Key + " = " + pair.Value + "\n";
Console.WriteLine(error);
}
LogWriter(error, true);
}
}
Method to DELETE the files
private static void DeleteFile(string sInputFilename)
{
try
{
if (_TestingOnly)
{
Console.WriteLine("TESTING ONLY! File: " + sInputFilename + " would have been deleted.");
}
else
{
File.Delete(sInputFilename);
}
}
catch (Exception ex)
{
Console.Write(ex.ToString());
LogWriter(ex.ToString(), true);
}
}
This may be caused by your files not being closed after the call to EncryptFile. In your original code, if you hit an exception in EncryptFile the streams would be left open if the exception happens before the call to Close. Using Using statements makes this easier but you can also put the Close in a finally block and close the streams if they're not null.
Here's an example using Using:
private static void EncryptFile(string sInputFilename,
string sOutputFilename, string sKey)
{
using(FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read),
FileStream fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write))
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
using(CryptoStream cryptostream =
new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write))
{
try
{
byte[] bytearrayinput = System.IO.File.ReadAllBytes(sInputFilename);
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
}
catch (Exception ex)
{
string error = "";
foreach (DictionaryEntry pair in ex.Data)
{
error += pair.Key + " = " + pair.Value + "\n";
Console.WriteLine(error);
}
LogWriter(error, true);
}
}
}
}
Edit
My proposed code will solve the issue of the file stream being left open. However, the root of the issue is that the system throws an OutOfMemoryException while reading the file if it's large. The original code would read all the bytes then read the bytes again into the same buffer, which is a waste of memory and a waste of time. Below is a corrected version:
private static void EncryptFile(string sInputFilename,
string sOutputFilename, string sKey)
{
using(FileStream fsInput = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read),
fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write))
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
using(CryptoStream cryptostream =
new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write))
{
byte[] buffer = new byte[2048];
int readCount = 0;
try
{
while ((readCount = fsInput.Read(buffer, 0, 2048)) > 0)
{
cryptostream.Write(buffer, 0, readCount);
}
}
catch (Exception ex)
{
string error = "";
foreach (DictionaryEntry pair in ex.Data)
{
error += pair.Key + " = " + pair.Value + "\n";
Console.WriteLine(error);
}
LogWriter(error, true);
}
}
}
}
You should consider using using statements for all objects that implement IDisposable. This will ensure that they are closed and disposed at the end of the using block:
private static void EncryptFile(string sInputFilename, string sOutputFilename,
string sKey)
{
using (var fsInput = new FileStream(sInputFilename, FileMode.Open,
FileAccess.Read))
using (var fsEncrypted = new FileStream(sOutputFilename, FileMode.Create,
FileAccess.Write))
using (var desCryptoProvider = new DESCryptoServiceProvider())
{
desCryptoProvider.Key = Encoding.ASCII.GetBytes(sKey);
desCryptoProvider.IV = Encoding.ASCII.GetBytes(sKey);
using (var encryptor = desCryptoProvider.CreateEncryptor())
using (var cryptoStream = new CryptoStream(fsEncrypted, encryptor,
CryptoStreamMode.Write))
{
try
{
var bytearrayinput = File.ReadAllBytes(sInputFilename);
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptoStream.Write(bytearrayinput, 0, bytearrayinput.Length);
}
catch (Exception ex)
{
var errors = new StringBuilder();
foreach (var pair in ex.Data)
{
errors.AppendLine(string.Format("{0} = {1}", pair.Key, pair.Value));
}
Console.WriteLine(errors.ToString());
LogWriter(errors.ToString(), true);
}
}
}
}
It's not exactly an answer, but may help; a simple method to check if a file is locked:
bool IsFileAvailable(string fileName)
{
FileStream stream = null;
try
{
FileInfo fileInfo = new FileInfo(fileName);
stream = fileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
// File is not present, or locked by another process
return false;
}
finally
{
if (stream != null)
stream.Close();
}
// File is present and not locked
return true;
}
How to Zip a folder using ICSharplib.
Is there any way I can add a encrypt password while zipping it ?
There is no option that I can use any other dll. Have to use only ICSharplib.
Currently I am using this code block
private static void CompressFiles(string folderPath) {
string zipOutput = #"C:\temp\myoutput.zip";
try {
using (ZipOutputStream zs = new ZipOutputStream(File.Create(zipOutput))) {
zs.SetLevel(9); // 0-9 (9 being best compression)
foreach (string file in Directory.GetFiles(folderPath)) {
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
using (FileStream fs = File.OpenRead(file)) {
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
entry.Size = buffer.Length; // This is very important
zs.PutNextEntry(entry);
zs.Write(buffer, 0, buffer.Length);
}
}
zs.Finish();
zs.Close();
}
}
catch { throw; }
}
It can zip all the files in the folder.
But What I want is to zip the whole folder.
Like the folders in side that folder also be included in the zip file .
Thanks in advance
Use the FastZip object.
ICSharpCode.SharpZipLib.Zip.FastZip z = new ICSharpCode.SharpZipLib.Zip.FastZip();
z.CreateEmptyDirectories = true;
z.CreateZip("F:\\ZipTest.zip", "F:\\ZipTest\\", true, "");
if (File.Exists("F:\\ZipTest.zip"))
Console.WriteLine("Done");
else
Console.WriteLine("Failed");
I use following code:
public static bool ZipIt(string sourcePath, string destinationPath)
{
List<string> ListOfFiles = GetListOfFiles(sourcePath);
try
{
string OutPath = destinationPath + ".zip";
int TrimLength = (Directory.GetParent(sourcePath)).ToString().Length;
TrimLength += 1;
//remove '\'
FileStream ostream;
byte[] obuffer;
ZipOutputStream oZipStream = new ZipOutputStream(System.IO.File.Create(OutPath));
oZipStream.Password = EncodePassword("Password");
oZipStream.SetLevel(9);
// 9 = maximum compression level
ZipEntry oZipEntry;
foreach (string Fil in ListOfFiles.ToArray()) // for each file, generate a zipentry
{
oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength));
oZipStream.PutNextEntry(oZipEntry);
if (!Fil.EndsWith(#"/")) // if a file ends with '/' its a directory
{
ostream = File.OpenRead(Fil);
obuffer = new byte[ostream.Length];
ostream.Read(obuffer, 0, obuffer.Length);
oZipStream.Write(obuffer, 0, obuffer.Length);
ostream.Close();
}
}
oZipStream.Finish();
oZipStream.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
public static string EncodePassword(string originalPassword)
{
Byte[] encodedBytes;
encodedBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
return BitConverter.ToString(encodedBytes);
}
Currently my program can encrypt and decrypt however when ever i key in wrong but same digits of password the program will hang. was wondering how to i solve it?
Eg. correct password is 12345678 but i key in 12341234 which is same 8 digit but wrong key the decrpytion will hang
//Encrypt Method
public bool DESEncrypt(String input, String output, String key)
{
bool success = false;
try
{
int requiredLength = 8;
FileStream fsInput = new FileStream(input, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted = new FileStream(output, FileMode.Create, FileAccess.Write);
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Padding = PaddingMode.PKCS7;
if (key.Length < requiredLength)
{
key = key.PadRight(requiredLength);
}
else if (key.Length > requiredLength)
{
key = key.Substring(0, requiredLength);
}
DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
DES.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform desEncrypt = DES.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(fsEncrypted, desEncrypt, CryptoStreamMode.Write);
byte[] byteInput = new byte[fsInput.Length];
fsInput.Read(byteInput, 0, byteInput.Length);
cryptoStream.Write(byteInput, 0, byteInput.Length);
cryptoStream.Flush();
cryptoStream.Close();
fsInput.Close();
fsEncrypted.Close();
success = true;
MessageBox.Show("Lock Success!");
}
catch (Exception ex)
{
success = false;
MessageBox.Show("Encryption Unsuccessful!" + ex);
//To Be Continue.....
//File being processed error
//try .Dispose()?
}
return success;
}
//Decrypt method
public bool Decrypt(String input, String output, String key)
{
bool success = false;
try
{
int requiredLength = 8;
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Padding = PaddingMode.PKCS7;
if (key.Length < requiredLength)
{
key = key.PadRight(requiredLength);
}
else if (key.Length > requiredLength)
{
key = key.Substring(0, requiredLength);
}
//Set secret key For DES algorithm.
DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
//Set initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(key);
//Create a file stream to read the encrypted file back.
FileStream fsInput = new FileStream(input, FileMode.Open, FileAccess.Read);
//Create a DES decryptor from the DES instance.
ICryptoTransform desDecrypt = DES.CreateDecryptor();
//Create crypto stream set to read and do a
//DES decryption transform on incoming bytes.
CryptoStream cryptostreamDecr = new CryptoStream(fsInput, desDecrypt, CryptoStreamMode.Read);
//Print the contents of the decrypted file.
BinaryWriter bw = new BinaryWriter(new FileStream(output, FileMode.Create, FileAccess.Write));
byte[] buffer = new byte[500];
int bytesRead = -1;
while (true)
{
bytesRead = cryptostreamDecr.Read(buffer, 0, 500);
if (bytesRead == 0)
{
break;
}
bw.Write(buffer, 0, bytesRead);
}
//StreamWriter fsDecrypted = new StreamWriter(output);
//fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
bw.Flush();
fsInput.Close();
cryptostreamDecr.Close();
bw.Close();
success = true;
MessageBox.Show("Unlock Success!");
}
catch (Exception ex)
{
success = false;
MessageBox.Show("Decryption Unsuccessful!" + ex);
//Try memory stream
}
return success;
}
}
}
As I said in the comment I don't think the problem is going to be with the decryption but with how you process the output.
However, the problem you have is that you need to be able to identify when an incorrect key has been used. The simplest way to do this is to include a fixed known value at the beginning of whatever you are encrypting before you encrypt it. Then, when you decrypt, you can check to see if the plain text begins with the known value and then discard the known value if it does and raise an error if it doesn't.