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.
Related
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);
}
}
}
}
My problem is that the created encrypted zip file is unable to open after decrypting it. It says the compressed file is invalid. File it self almost doubled it's initial space after decrypting from 15 KB to 27 KB. The problem occours on zip files, when I encrypted and decryped a xml file it worked just fine. Below my whole code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace EDI
{
public class EncryptionHelper
{
public void Main()
{
var file = #"C:\Temp\test.zip";
AesCryptoServiceProvider AES = new AesCryptoServiceProvider();
AES.Padding = PaddingMode.PKCS7;
AES.Mode = CipherMode.CBC;
AES.BlockSize = 128;
AES.KeySize = 128;
AES.GenerateKey();
AES.GenerateIV();
var key = AES.Key;
var iv = AES.IV;
encryptAES(AES, file, key, iv);
decryptAES(AES, file + ".encrypted", key, iv);
}
public void encryptAES(SymmetricAlgorithm algo, string filePath, byte[] key, byte[] IV)
{
using (FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (FileStream fout = new FileStream(filePath + ".encrypted", FileMode.OpenOrCreate, FileAccess.Write))
{
using (ICryptoTransform crypt = algo.CreateEncryptor(key, IV))
{
using (CryptoStream crStream = new CryptoStream(fout, crypt, CryptoStreamMode.Write))
{
fin.CopyTo(crStream);
}
}
}
}
}
public void decryptAES(SymmetricAlgorithm algo, string filePath, byte[] key, byte[] IV)
{
using (FileStream fStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
using (ICryptoTransform crypt = algo.CreateDecryptor(key, IV))
{
using (CryptoStream crStream = new CryptoStream(fStream, crypt, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(crStream))
{
string data = reader.ReadToEnd();
File.WriteAllText(filePath.Replace(".encrypted", ".restored"), data);
}
}
}
}
}
}
}
Edit to show the fix.
using (FileStream writer = new FileStream(filePath + ".decrypted", FileMode.Create, FileAccess.Write))
// using (Read reader = new StreamReader(crStream))
{
// string data = reader.ReadToEnd();
// File.WriteAllText(filePath.Replace(".encrypted", ".restored"), data);
crStream.CopyTo(writer);
}
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);
}
}
When encrypting and decrypting text files, the code works fine.
But when encrypting binary and zip files, file size almost doubled after decryption. For example, a 2.06mb bin.exe became 3.69mb after decryption; a 4mb zip file became 7+mb after decryption.
Is this because of the PaddingMode? What PaddingMode should I set to work with all types of files? How to solve this problem?
private async Task RunEncrypt(string srcfile)
{
string data;
using (StreamReader sr = new StreamReader(srcfile))
{
data = sr.ReadToEnd();
}
byte[] enc_data = await Program.myEncrypt(data);
}
static async Task<byte[]> myEncrypt(string toEncStr)
{
byte[] encrypted;
using (Aes encaes = Aes.Create())
{
try
{
//store key to key.txt
FileStream fs = new FileStream("key.txt", FileMode.OpenOrCreate);
fs.Write(encaes.Key, 0, encaes.Key.Length);
fs.Write(encaes.IV, 0, encaes.IV.Length);
fs.Close();
}
catch ( Exception e)
{
Console.WriteLine("Recording encryption keys failed!{0}.", e.Message);
Environment.Exit(0);
}
encaes.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = encaes.CreateEncryptor(encaes.Key, encaes.IV);
try
{
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(toEncStr);
}
}
encrypted = msEncrypt.ToArray();
}
return encrypted;
}
catch (Exception e)
{
Console.WriteLine("Encryption failed!{0}.", e.Message);
return Encoding.UTF8.GetBytes("null");
}
}
}
private async Task RunDecrypt(byte[] inbytes)
{
try
{
string write_data = await myDecrypt(inbytes);
using (StreamWriter sw = new StreamWriter("test.exe", true))
{
sw.Write(write_data);
sw.Close();
}
}
catch (Exception e)
{
}
}
async Task<string> myDecrypt(byte[] toDecBytes)
{
try
{
string decrypted;
using (Aes dec = Aes.Create())
{
byte[] Key = new byte[dec.Key.Length];
byte[] IV = new byte[dec.IV.Length];
//read key from key.txt
FileStream fsread = new FileStream("key.txt", FileMode.Open);
fsread.Read(Key, 0, Key.Length);
fsread.Read(IV, 0, IV.Length);
fsread.Close();
dec.Key = Key;
dec.IV = IV;
dec.Padding = PaddingMode.PKCS7;
ICryptoTransform decryptor = dec.CreateDecryptor(dec.Key, dec.IV);
using (MemoryStream msDecrypt = new MemoryStream(toDecBytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
decrypted = srDecrypt.ReadToEnd();
return decrypted;
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Decryption failed! {0}.", e.Message);
return #"null";
}
}
By using a StreamReader and StreamWriter, you are treating the file content as text. To support binary files, read/write directly from/to the source/target stream instead.
I'm currently learning about crypters and this is what I've learned so far.
A crypter consists of a builder and a stub.
The builders role is to encrypt a file and the stub wraps the file
and makes it run in a buffer aka in the memory of the machine it is being decrypted on.
(Please do correct if I am wrong)
I have created my File Encrypter (The builder) and to be honest I have no idea how to create a stub.. I've been looking around the entire day but all I can find are these really old Console applications not explaining anything really..
So my question is..
How do I wrap my current file encrypter with a stub.. or how do I create a stub. Not to sure how to form that question since I am new to stubs.
Here is my file encrypter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows;
using Microsoft.Win32;
using System.Security.Cryptography;
using System.IO;
namespace FileEncrypter
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string key;
public MainWindow()
{
InitializeComponent();
key = generateKey();
}
public string generateKey()
{
DESCryptoServiceProvider desCrypto = (DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
}
private void EncryptBtn_Click(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
inputencryptFileTextBox.Text = ofd.FileName;
SaveFileDialog sfd = new SaveFileDialog();
sfd.ShowDialog();
outputencryptFileTextBox.Text = sfd.FileName;
encrypt(inputencryptFileTextBox.Text, outputencryptFileTextBox.Text, key);
MessageBox.Show("File has been encrypted.", "File");
}
catch(Exception encEx)
{
MessageBox.Show(encEx.ToString());
}
}
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();
}
private void DecryptBtn_Click(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
inputdecryptFileTextBox.Text = ofd.FileName;
SaveFileDialog sfd = new SaveFileDialog();
sfd.ShowDialog();
outputdecryptFileTextBox.Text = sfd.FileName;
decrypt(inputdecryptFileTextBox.Text, outputdecryptFileTextBox.Text, key);
MessageBox.Show("File has been decrypted.", "File");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void decrypt(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.CreateDecryptor(), 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();
}
}
}
The stub can be something like a small project with the encrypted part as resource. When the stub is loaded, it will decript the assembly from the resource and uses reflection to find the 'main entry point'. The problem is, how to keep the private key.... uh... private..
I've not heard of a stub used in that context. I only hear it in terms of testing or adding "place holder" APIs.
I think what you are asking for is how to have the builder use interface that could wrap a file or wrap a memory stream? If so, your encrypt method could accept an interface instead of a string. That interface can provide an API for reading and writing the data. When you are calling the encrypt method, you can either new up the file implementation of the interface or the in memory implementation and pass it into encrypt.
Since you are dealing with an interface in the encrypt method, it will treat both objects equally.
Alternatively, you could also just accept a Stream. Then you can pass in a MemoryStream or a FileStream.