I have 1 TextBox in which the encryption key is entered, 2 ButtonEnc and ButtonDec buttons. When using saveFileDialog, nothing happens, an empty file is saved, and the Encrypt method error Encryption failed!", "Error.
I can't save encryption/Decryption file.
How can I change the code so that everything works as it should?
private void ButtonEnc_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
Microsoft.Win32.SaveFileDialog dlg1 = new Microsoft.Win32.SaveFileDialog();
Nullable<bool> result = dlg.ShowDialog();
Nullable<bool> result1 = dlg1.ShowDialog();
sKey = TextBox1.Text;
if (result == true)
{
string inputFile = dlg.FileName;
dlg1.Filter = "aes documents (.aes)|*.aes";
if (result1 == true)
{
sKey = TextBox1.Text;
string outputFile = dlg1.FileName;
EncryptFile(inputFile, outputFile);
}
}
}
private void EncryptFile(string inputFile, string outputFile)
{
try
{
sKey = TextBox1.Text;
string password = sKey;
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch
{
MessageBox.Show("Encryption failed!", "Error");
}
}
private void DecryptFile(string inputFile, string outputFile)
{
{
sKey = TextBox1.Text;
string password = sKey;
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
}
private void ButtonDec_Click_1(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog dlg1 = new Microsoft.Win32.SaveFileDialog();
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
Nullable<bool> result = dlg.ShowDialog();
Nullable<bool> result1 = dlg1.ShowDialog();
sKey = TextBox1.Text;
dlg.Filter = "aes files |*.aes";
dlg.Multiselect = false;
if (result == true)
{
string inputFile = dlg.FileName;
if (result1 == true)
{
string outputFile = dlg1.FileName;
DecryptFile(inputFile, outputFile);
}
}
}
}
Related
i have tried the following code to encrypt and decrypt files using asp.net c# rijndael managed. all of the images notepad is encrypted and decrypted successfully, when it comes to doc or docx file it always showing damaged file when i tried to open. but if i click resolve this issue in microsoft word, then the file is back. what could go wrong in the code. please help me
public void EncryptFile(string password, string inputFile, string outputFile)
{
try
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password.Trim());
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch(Exception err)
{
System.Diagnostics.Debug.WriteLine(err);
}
}
public void DecryptFile(string password, string inputFile, string outputFile)
{
try
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password.Trim());
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Create);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
catch(Exception err)
{
System.Diagnostics.Debug.WriteLine(err);
}
}
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'm trying to encrypt image files using Rijndael encryption and I must be doing something wrong because the decrypted files are coming out with extra data at the front of the file any maybe a little extra at the end. I'm fairly new to this encryption algorithm so I'm pretty sure I'm just missing something simple.
Examples using text files
Input file
"the quick brown fox jumped over the lazy yellow dog"
Output file when I try to put a generated IV at the front of the file(\0=null)
"ÚñjÐæƒÊW®ï¡_Ü&ßthe\0 quick brown fox jumped over the lazy yellow dog"
Output file when I try to put an IV that is equal to my Key at front
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0the\0\0\0\0\0\0 quick brown fox jumped over the lazy yellow dog"
Output file when I use an IV that is equal to my Key and put nothing at front of file
"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0the\0\0\0\0\0\0 quick brown fox jumped over the lazy yellow dog"
CODE
private RijndaelManaged GetCipher(byte[] key, bool forEncrypt)
{
RijndaelManaged rijndaelCipher;
rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 0x80;
rijndaelCipher.BlockSize = 0x80;
rijndaelCipher.Key = key;
/* if (forEncrypt)
rijndaelCipher.GenerateIV();
else
rijndaelCipher.IV = new byte[16];*/
rijndaelCipher.IV = _imageKey;
return rijndaelCipher;
}
public void DecryptStamp(Stamp stampToDecrypt, string decrpytedStampFilePath)
{
RijndaelManaged rijndaelCipher;
FileStream inputStream = null;
FileStream outputStream = null;
CryptoStream encryptSteam = null;
byte[] block;
int numberRead;
ICryptoTransform transform;
if (!File.Exists(stampToDecrypt.Path))
throw new FileNotFoundException(stampToDecrypt.Path + " does not exist");
rijndaelCipher = this.GetCipher(_imageKey, false);
block = new byte[16];
try
{
inputStream = File.Open(stampToDecrypt.Path, FileMode.Open, FileAccess.Read);
outputStream = File.Open(decrpytedStampFilePath, FileMode.Create, FileAccess.Write);
//inputStream.Read(rijndaelCipher.IV, 0, rijndaelCipher.IV.Length);
transform = rijndaelCipher.CreateDecryptor();
encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);
while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
{
Console.WriteLine(numberRead.ToString());
encryptSteam.Write(block, 0, numberRead);
}
}
finally
{
rijndaelCipher.Clear();
rijndaelCipher.Dispose();
if (encryptSteam != null)
encryptSteam.Dispose();
if (outputStream != null)
outputStream.Dispose();
if (inputStream != null)
inputStream.Dispose();
}
}
public Stamp EncryptStampToStampFolder(string stampFileToEncrpyt)
{
Configuration config;
Stamp stampToEncrypt;
RijndaelManaged rijndaelCipher;
string encryptedFilePath;
if (!File.Exists(stampFileToEncrpyt))
throw new FileNotFoundException(stampFileToEncrpyt + " does not exist");
config = Configuration.GetProgramInstance();
encryptedFilePath = Path.Combine(config.StampFolder, Path.GetFileNameWithoutExtension(stampFileToEncrpyt) + ".stmp");
stampToEncrypt = new Stamp(Path.GetFileNameWithoutExtension(stampFileToEncrpyt), encryptedFilePath);
rijndaelCipher = this.GetCipher(_imageKey, true);
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
FileStream inputStream = null;
FileStream outputStream = null;
CryptoStream encryptSteam = null;
byte[] block = new byte[16];
int numberRead;
try
{
inputStream = File.Open(stampFileToEncrpyt, FileMode.Open, FileAccess.Read);
outputStream = File.Open(encryptedFilePath, FileMode.Create, FileAccess.Write);
//outputStream.Write(rijndaelCipher.IV, 0, 16);
encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);
encryptSteam.Write(block, 0, block.Length);
while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
{
encryptSteam.Write(block, 0, numberRead);
}
}
finally
{
rijndaelCipher.Clear();
rijndaelCipher.Dispose();
if (encryptSteam != null)
encryptSteam.Dispose();
if (outputStream != null)
outputStream.Dispose();
if (inputStream != null)
inputStream.Dispose();
}
return stampToEncrypt;
}
public struct Stamp
{
public string Name,
Path;
public Stamp(string StampName, string StampPath)
{
Name = StampName;
Path = StampPath;
}
}
CODE post fix
private RijndaelManaged GetCipher(byte[] key, bool forEncrypt)
{
RijndaelManaged rijndaelCipher;
rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 0x80;
rijndaelCipher.BlockSize = 0x80;
rijndaelCipher.Key = key;
if (forEncrypt)
rijndaelCipher.GenerateIV();
else
rijndaelCipher.IV = new byte[16];
//rijndaelCipher.IV = _imageKey;
return rijndaelCipher;
}
public void DecryptStamp(Stamp stampToDecrypt, string decrpytedStampFilePath)
{
RijndaelManaged rijndaelCipher;
FileStream inputStream = null;
FileStream outputStream = null;
CryptoStream encryptSteam = null;
byte[] block;
int numberRead;
ICryptoTransform transform;
if (!File.Exists(stampToDecrypt.Path))
throw new FileNotFoundException(stampToDecrypt.Path + " does not exist");
rijndaelCipher = this.GetCipher(_imageKey, false);
block = new byte[16];
try
{
inputStream = File.Open(stampToDecrypt.Path, FileMode.Open, FileAccess.Read);
outputStream = File.Open(decrpytedStampFilePath, FileMode.Create, FileAccess.Write);
inputStream.Read(rijndaelCipher.IV, 0, rijndaelCipher.IV.Length);
transform = rijndaelCipher.CreateDecryptor();
encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);
while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
{
encryptSteam.Write(block, 0, numberRead);
}
}
finally
{
rijndaelCipher.Clear();
rijndaelCipher.Dispose();
if (encryptSteam != null)
encryptSteam.Dispose();
if (outputStream != null)
outputStream.Dispose();
if (inputStream != null)
inputStream.Dispose();
}
}
public Stamp EncryptStampToStampFolder(string stampFileToEncrpyt)
{
Configuration config;
Stamp stampToEncrypt;
RijndaelManaged rijndaelCipher;
string encryptedFilePath;
if (!File.Exists(stampFileToEncrpyt))
throw new FileNotFoundException(stampFileToEncrpyt + " does not exist");
config = Configuration.GetProgramInstance();
encryptedFilePath = Path.Combine(config.StampFolder, Path.GetFileNameWithoutExtension(stampFileToEncrpyt) + ".stmp");
stampToEncrypt = new Stamp(Path.GetFileNameWithoutExtension(stampFileToEncrpyt), encryptedFilePath);
rijndaelCipher = this.GetCipher(_imageKey, true);
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
FileStream inputStream = null;
FileStream outputStream = null;
CryptoStream encryptSteam = null;
byte[] block = new byte[16];
int numberRead;
try
{
inputStream = File.Open(stampFileToEncrpyt, FileMode.Open, FileAccess.Read);
outputStream = File.Open(encryptedFilePath, FileMode.Create, FileAccess.Write);
outputStream.Write(rijndaelCipher.IV, 0, 16);
encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);
//encryptSteam.Write(block, 0, block.Length); this line was the problem in the orginal code
while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
{
encryptSteam.Write(block, 0, numberRead);
}
}
finally
{
rijndaelCipher.Clear();
rijndaelCipher.Dispose();
if (encryptSteam != null)
encryptSteam.Dispose();
if (outputStream != null)
outputStream.Dispose();
if (inputStream != null)
inputStream.Dispose();
}
return stampToEncrypt;
}
public struct Stamp
{
public string Name,
Path;
public Stamp(string StampName, string StampPath)
{
Name = StampName;
Path = StampPath;
}
}
New Code's output
"7p¶¼oò¾½G€¢9±hfox\0\0 jumped over the lazy yellow dog"
The problem was three fold.
1)Extra data being written during encryption
2)The IV at the beginning of the file was being overwritten
3)The IV was not being read properly on decryption
CODE Fixed
private RijndaelManaged GetCipher(byte[] key, bool forEncrypt)
{
RijndaelManaged rijndaelCipher;
rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.PKCS7;
rijndaelCipher.KeySize = 0x80;
rijndaelCipher.BlockSize = 0x80;
rijndaelCipher.Key = key;
if (forEncrypt)
rijndaelCipher.GenerateIV();
else
rijndaelCipher.IV = new byte[16];
//rijndaelCipher.IV = _imageKey;
return rijndaelCipher;
}
public void DecryptStamp(Stamp stampToDecrypt, string decrpytedStampFilePath)
{
RijndaelManaged rijndaelCipher;
FileStream inputStream = null;
FileStream outputStream = null;
CryptoStream encryptSteam = null;
byte[] block;
int numberRead;
ICryptoTransform transform;
if (!File.Exists(stampToDecrypt.Path))
throw new FileNotFoundException(stampToDecrypt.Path + " does not exist");
rijndaelCipher = this.GetCipher(_imageKey, false);
block = new byte[16];
try
{
inputStream = File.Open(stampToDecrypt.Path, FileMode.Open, FileAccess.Read);
outputStream = File.Open(decrpytedStampFilePath, FileMode.Create, FileAccess.Write);
//This line was wrong because rijndaelCipher.IV never filled
//inputStream.Read(rijndaelCipher.IV, 0, rijndaelCipher.IV.Length);
inputStream.Read(block, 0, block.Length);
rijndaelCipher.IV = block;
block = new byte[16];
transform = rijndaelCipher.CreateDecryptor();
encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);
while ((numberRead = inputStream.Read(block, 0, block.Length)) > 0)
{
encryptSteam.Write(block, 0, numberRead);
}
}
finally
{
rijndaelCipher.Clear();
rijndaelCipher.Dispose();
if (encryptSteam != null)
encryptSteam.Dispose();
if (outputStream != null)
outputStream.Dispose();
if (inputStream != null)
inputStream.Dispose();
}
}
public Stamp EncryptStampToStampFolder(string stampFileToEncrpyt)
{
Configuration config;
Stamp stampToEncrypt;
RijndaelManaged rijndaelCipher;
string encryptedFilePath;
if (!File.Exists(stampFileToEncrpyt))
throw new FileNotFoundException(stampFileToEncrpyt + " does not exist");
config = Configuration.GetProgramInstance();
encryptedFilePath = Path.Combine(config.StampFolder, Path.GetFileNameWithoutExtension(stampFileToEncrpyt) + ".stmp");
stampToEncrypt = new Stamp(Path.GetFileNameWithoutExtension(stampFileToEncrpyt), encryptedFilePath);
rijndaelCipher = this.GetCipher(_imageKey, true);
ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
FileStream inputStream = null;
FileStream outputStream = null;
CryptoStream encryptSteam = null;
byte[] block = new byte[16];
int numberRead;
try
{
inputStream = File.Open(stampFileToEncrpyt, FileMode.Open, FileAccess.Read);
outputStream = File.Open(encryptedFilePath, FileMode.Create, FileAccess.Write);
outputStream.Write(rijndaelCipher.IV, 0, IV.Length);
//This had to be changed so that the IV was not overwitten
//encryptSteam = new CryptoStream(outputStream, transform, CryptoStreamMode.Write);
encryptSteam = new CryptoStream(inputStream, transform, CryptoStreamMode.Read);
//this line was a problem in the orginal code that caused extra data to be added to the encrypted file
//encryptSteam.Write(block, 0, block.Length);
while ((numberRead = encryptSteam.Read(block, 0, block.Length)) > 0)
{
outputStream.Write(block, 0, numberRead);
}
}
finally
{
rijndaelCipher.Clear();
rijndaelCipher.Dispose();
if (encryptSteam != null)
encryptSteam.Dispose();
if (outputStream != null)
outputStream.Dispose();
if (inputStream != null)
inputStream.Dispose();
}
return stampToEncrypt;
}
public struct Stamp
{
public string Name,
Path;
public Stamp(string StampName, string StampPath)
{
Name = StampName;
Path = StampPath;
}
}
Here's what I do to decrypt:
private RijndaelManaged GetAesProvider(Stream stm, bool isEncryption)
{
byte[] finalKey = GetFinalKey();
// GetIV either gets salt on encryption and writes it into stm
// or reads it from stm if it's decryption
byte[] iv = GetIV(stm, isEncryption);
RijndaelManaged aes = new RijndaelManaged();
aes.BlockSize = kAesBlockSizeInBytes * 8;
aes.IV = iv;
aes.Key = finalKey;
aes.Mode = CipherMode.CBC;
return aes;
}
public override Stream GetDecryptionStream(Stream source)
{
if (source.Length <= kIVSize)
{
return new EmptyStream();
}
RijndaelManaged aes = GetAesProvider(source, false);
ICryptoTransform xform = aes.CreateDecryptor(aes.Key, aes.IV);
return new CryptoStream(source, xform, CryptoStreamMode.Read);
}
In c#.net, when im trying to decrypt the file it shows me this error but it works for encryption.
ERROR: The process cannot access the file SecureDownloadManager.log because it is being used by another process
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
namespace Encryption
{
public partial class Form1 : Form
{
string inputFile;
string outputFile;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//EncryptFile();
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "All Files (*.*)|";
dialog.InitialDirectory = #"Desktop";
dialog.Title = "Please select a file to encrypt.";
dialog.ShowDialog();
inputFile = dialog.FileName;
outputFile = inputFile;
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{ //Decrypt File
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "All Files (*.*)|";
dialog.InitialDirectory = #"Desktop";
dialog.Title = "Please select a file to decrypt.";
dialog.ShowDialog();
inputFile = dialog.FileName;
outputFile = inputFile;
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
FileStream fsCrypt = new FileStream(inputFile, FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateDecryptor(key, key),
CryptoStreamMode.Read);
FileStream fsOut = new FileStream(outputFile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Try the following code and let me know if it resolves the problem.
//EncryptFile();
try
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "All Files (*.*)|";
dialog.InitialDirectory = #"Desktop";
dialog.Title = "Please select a file to encrypt.";
dialog.ShowDialog();
inputFile = dialog.FileName;
outputFile = inputFile;
string password = #"myKey123"; // Your Key Here
UnicodeEncoding UE = new UnicodeEncoding();
byte[] key = UE.GetBytes(password);
string cryptFile = outputFile;
using (FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create))
{
RijndaelManaged RMCrypto = new RijndaelManaged();
using (CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key, key),
CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
The error is due to the objects not being completely disposed. You need to use a 'using' clause to release objects after use.
You can use the following code that uses FileStream instead:
System.IO.File.WriteAllBytes(outputFile);
which replaces:
FileStream fsOut = new FileStream(outputFile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
int data;
while ((data = cs.ReadByte()) != -1)
fsOut.WriteByte((byte)data);
fsOut.Close();
cs.Close();
fsCrypt.Close();
I hope it resolves your issue.
I can read an write my serialized class fine until I try to encrypt / decrypt... here is a snippet of my code:
public class ShelfCache
{
public Shelf Data;
public ShelfCache()
{
Data = new Shelf();
}
public void Write(string Filename)
{
XmlSerializer xsl = new XmlSerializer(typeof(Shelf));
TextWriter xslWriter = new StreamWriter(Filename);
xsl.Serialize(xslWriter, Data);
xslWriter.Flush();
xslWriter.Close();
}
public void Read(string Filename)
{
Data = new Shelf();
XmlSerializer xsl = new XmlSerializer(typeof(Shelf));
TextReader xslReader = new StreamReader(Filename);
Data = (Shelf)xsl.Deserialize(xslReader);
xslReader.Close();
}
public void WriteEncrypted(string Filename, string EncryptionKey = "")
{
string _Key = EncryptionKey + Environment.ExpandEnvironmentVariables("%USERNAME%%COMPUTERNAME%123456789ABCDEF0123456789abcdef").Substring(0, 32);
string _IV = Environment.ExpandEnvironmentVariables("%COMPUTERNAME%123456789abcdef").Substring(0, 16);
byte[] Key = Encoding.UTF8.GetBytes(_Key);
byte[] IV = Encoding.UTF8.GetBytes(_IV);
FileStream CacheStream = new FileStream(Filename, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
RijndaelManaged CryptoProvider = new RijndaelManaged();
ICryptoTransform CacheTransform = CryptoProvider.CreateEncryptor(Key, IV);
CryptoStream EncryptionStream = new CryptoStream(CacheStream, CacheTransform, CryptoStreamMode.Write);
XmlSerializer xsl = new XmlSerializer(typeof(Shelf));
xsl.Serialize(EncryptionStream, Data);
EncryptionStream.Flush();
CacheStream.Close();
}
public void ReadEncrypted(string Filename, string EncryptionKey = "")
{
string _Key = EncryptionKey + Environment.ExpandEnvironmentVariables("%USERNAME%%COMPUTERNAME%123456789ABCDEF0123456789abcdef").Substring(0, 32);
string _IV = Environment.ExpandEnvironmentVariables("%COMPUTERNAME%123456789abcdef").Substring(0, 16);
byte[] Key = Encoding.UTF8.GetBytes(_Key);
byte[] IV = Encoding.UTF8.GetBytes(_IV);
FileStream CacheStream = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
RijndaelManaged CryptoProvider = new RijndaelManaged();
ICryptoTransform CacheTransform = CryptoProvider.CreateEncryptor(Key, IV);
CryptoStream DecryptionStream = new CryptoStream(CacheStream, CacheTransform, CryptoStreamMode.Read);
XmlSerializer xsl = new XmlSerializer(typeof(Shelf));
Data = (Shelf)xsl.Deserialize(DecryptionStream);
CacheStream.Close();
}
}
I get the exception "There is an error in XML document (1 1)." with an inner exception "Data at the root level is invalid. Line 1, position 1." on the line:
Data = (Shelf)xsl.Deserialize(DecryptionStream);
This is what I ended up doing (I don't like the solution, but it works)...
public class ShelfCache
{
public Shelf Data;
public ShelfCache()
{
Data = new Shelf();
}
public void Write(string Filename)
{
XmlSerializer CacheSerializer = new XmlSerializer(typeof(Shelf));
TextWriter CacheWriter = new StreamWriter(Filename);
CacheSerializer.Serialize(CacheWriter, Data);
CacheWriter.Flush();
CacheWriter.Close();
}
public void Read(string Filename)
{
Data = new Shelf();
XmlSerializer CacheSerializer = new XmlSerializer(typeof(Shelf));
TextReader CacheReader = new StreamReader(Filename);
Data = (Shelf)CacheSerializer.Deserialize(CacheReader);
CacheReader.Close();
}
public void WriteEncrypted(string Filename, string EncryptionKey = "")
{
string TempFile = System.IO.Path.GetTempFileName();
Write(TempFile);
EncryptFile(TempFile, Filename, EncryptionKey);
File.Delete(TempFile);
}
public void ReadEncrypted(string Filename, string EncryptionKey = "")
{
string TempFile = System.IO.Path.GetTempFileName();
DecryptFile(Filename, TempFile, EncryptionKey);
Read(TempFile);
File.Delete(TempFile);
}
private RijndaelManaged GetEncryptor(string Key = "", string Salt = "")
{
Key += Environment.ExpandEnvironmentVariables("%USERNAME%");
Salt += Environment.ExpandEnvironmentVariables("%COMPUTERNAME%");
Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(Key, Encoding.Unicode.GetBytes(Salt));
RijndaelManaged rijndaelCSP = new RijndaelManaged();
rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8);
rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8);
return rijndaelCSP;
}
private void EncryptFile(string Source, string Target, string EncryptionKey)
{
RijndaelManaged EncryptionProvider = GetEncryptor(EncryptionKey);
ICryptoTransform Encryptor = EncryptionProvider.CreateEncryptor();
FileStream SourceStream = new FileStream(Source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] SourceBytes = new byte[(int)SourceStream.Length];
SourceStream.Read(SourceBytes, 0, (int)SourceStream.Length);
FileStream TargetStream = new FileStream(Target, FileMode.Create, FileAccess.Write);
CryptoStream EncryptionStream = new CryptoStream(TargetStream, Encryptor, CryptoStreamMode.Write);
EncryptionStream.Write(SourceBytes, 0, (int)SourceStream.Length);
EncryptionStream.FlushFinalBlock();
EncryptionProvider.Clear();
EncryptionStream.Close();
SourceStream.Close();
TargetStream.Close();
}
private void DecryptFile(string Source, string Target, string EncryptionKey)
{
RijndaelManaged EncryptionProvider = GetEncryptor(EncryptionKey);
ICryptoTransform Decryptor = EncryptionProvider.CreateDecryptor();
FileStream SourceStream = new FileStream(Source, FileMode.Open, FileAccess.Read);
CryptoStream DecryptionStream = new CryptoStream(SourceStream, Decryptor, CryptoStreamMode.Read);
byte[] SourceBytes = new byte[(int)SourceStream.Length];
int DecryptionLength = DecryptionStream.Read(SourceBytes, 0, (int)SourceStream.Length);
FileStream TargetStream = new FileStream(Target, FileMode.Create, FileAccess.Write);
TargetStream.Write(SourceBytes, 0, DecryptionLength);
TargetStream.Flush();
EncryptionProvider.Clear();
DecryptionStream.Close();
SourceStream.Close();
TargetStream.Close();
}
}