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);
}
}
Related
I am using rijndael encryption method to encrypt configuration file to keep it safe in client system. But after encryption, when a new file is generated, it comes with admin credential and i am not able to read it.
public void EncryptFile(string inputFile, string outputFile)
{
try
{
string password = #"myKey"; // 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);
int data;
while ((data = fsIn.ReadByte()) != -1)
cs.WriteByte((byte)data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
FileInfo fi = new FileInfo(inputFile);
fi.Delete();
}
catch
{
Console.WriteLine("Encryption failed!", "Error");
}
}
I am using this method. When i run it in build mode it works perfectly but when i create a setup it fails and creates encrypted file with admin credential which i am not able to read. I am Using Install Shield 2013 limited edition.
I didn't want to seed the IV with the user given password. The question is if I've created the method of encrypting with a generated IV, is there anyway I could save the generated IV, to get it into the decryption method, without saving it into a database.
private void EncryptFile(string inputFile,string outputFile, string pass_input){
try
{
MessageBox.Show("FLAG 1");
UTF8Encoding UE = new UTF8Encoding();
//Represents a UTF-8 encoding of unicode characters
string password = pass_input;
// passed password through user input
byte[] key = UE.GetBytes(password);
//password parsed into bytes
string cryptFile = outputFile;
FileStream FScrypt = new FileStream(cryptFile, FileMode.Create);
//FScrypt is created where it creates a file to save output
RijndaelManaged RMcrypto = new RijndaelManaged();
//RMcrypto is created where new instance of RijndaelManaged Class is initialized
RMcrypto.GenerateIV();
CryptoStream cs = new CryptoStream(FScrypt, RMcrypto.CreateEncryptor(key,RMcrypto.IV), CryptoStreamMode.Write);
//CreateEncryptor from RMcrypto creates a symmetric Rijndael Encryptor object with specified key
FileStream fsIn = new FileStream(inputFile, FileMode.Open);
//fsIn Opens the input file
MessageBox.Show("FLAG 2");
int data;
while ((data = fsIn.ReadByte()) != -1)
//will read input file opened by fsIn
cs.WriteByte((byte)data);
MessageBox.Show("FLAG 3");
fsIn.Close();
cs.Close();
FScrypt.Close();
catch(Exception ex)
{
MessageBox.Show("Failed");
}
}
private void DecryptFile(string inputFile, string outputFile, string pass_input)
{
try
{
string password = pass_input; // Taking password input and storing in local string.
UTF8Encoding UE = new UTF8Encoding() //UnicodeEncoding Object UTF8
byte[] key = UE.GetBytes(password); // converting password to bytes
FileStream fsCrypt = new FileStream(inputFile, FileMode.Open); // Opens the file
RijndaelManaged RMCrypto = new RijndaelManaged(); //new RijndaelMaaged object
CryptoStream cs = new CryptoStream(fsCrypt, RMCrypto.CreateDecryptor(key, **"RMCrypto.IV"**), 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 ex)
{
MessageBox.Show("Failed");
}
}
One well used/accepted method is to prepend the IV to the encrypted data, the IV does not need to be secret.
while encrypting an audio file using C#, i got an exception that "Specified inetialisation vector(IV) does not match the block size of the algorithm". and i'm using Rijndael algorithm provided by the cryptography class. what i'm supposed to do to solve this exception?
my code is given below:
public void EncryptFile(string inputFile, string outputFile)
{
try
{
inputFile = textBox_path.Text;
String password = "keykey";
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();
MessageBox.Show("encryption is completed!!");
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
}
and my function call is:
There is a similar question here.
With Rijndael, you can choose the block sizes 128, 160, 192, 224, or 256 bits. Then you must choose an initialization vector of the same length:
using (RijndaelManaged rm = new RijndaelManaged())
{
rm.BlockSize = 128;
Rfc2898DeriveBytes keyDerivator = new Rfc2898DeriveBytes(password, salt, KeyGenIterationCount); //derive key and IV from password and salt using the PBKDF2 algorithm
rm.IV = keyDerivator.GetBytes(16); //16 bytes (128 bits, same as the block size)
rm.Key = keyDerivator.GetBytes(32);
//(encrypt here)
}
In any case, I would recommend using the AesCryptoServiceProvider class instead, since it's FIPS-compilant. Read more about the differences here: http://blogs.msdn.com/b/shawnfa/archive/2006/10/09/the-differences-between-rijndael-and-aes.aspx
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've used AESManaged Class to encrypt a zip file, but it couldn't be decompressed by winzip/7zip. I can only decompress it after decrypting in my code.
Below is the code I used to encrypt and decrypt. Anyone can help?
private static void EncryptFile(string input, string output, string pwd)
{
using (AesManaged aes = new AesManaged())
{
FileStream fsCrypt=null;
try
{
byte[] key = Encoding.UTF8.GetBytes(pwd);
fsCrypt = new FileStream(output, FileMode.Create);
using (CryptoStream cs = new CryptoStream(fsCrypt, aes.CreateEncryptor(key, key), CryptoStreamMode.Write))
{
using (FileStream fsIn = new FileStream(input, FileMode.Open))
{
int data;
while ((data = fsIn.ReadByte()) != -1)
{
cs.WriteByte((byte)data);
}
aes.Clear();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
aes.Clear();
}
finally
{
if(fsCrypt!=null)
{
fsCrypt.Dispose();
}
}
}
}
private static void DecryptFile(string input, string output, string pwd)
{
using (AesManaged aes = new AesManaged())
{
FileStream fsCrypt = null;
try
{
byte[] key = Encoding.UTF8.GetBytes(pwd);
fsCrypt = new FileStream(input, FileMode.Open);
{
using (FileStream fsOut = new FileStream(output, FileMode.Create))
{
using (CryptoStream cs = new CryptoStream(fsCrypt, aes.CreateDecryptor(key, key), CryptoStreamMode.Read))
{
int data;
while ((data = cs.ReadByte()) != -1)
{
fsOut.WriteByte((byte)data);
}
aes.Clear();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
aes.Clear();
}
finally
{
if (fsCrypt != null)
{
fsCrypt.Dispose();
}
}
}
}
You are overwriting the internal structure of a zip file with your encryption algorithm.
How could you expect that an external zip manager recognizes your encrypted file as a valid zip file?
If you really want to use a password protected zip file then use a library that can do this for you without destroying the zip file structure.
I recommend this library DotNetZip
It is not possible to unzip a file if the format is not that of zip. Once you encrypt a file you the format is no longer zip.
But it is possible to perform both encryption and compression in C#. For better compression ratio you would need to compress the file first and then encrypt.
You can use GZipstream to compress and the code you have depicted to encrypt.