When I am decrypting a text file the text file becomes empty - c#

guys, I'm new to this website and I'm a really new to programming any help would be awesome! Thanks Below are my code for encryption and decryption. Images and PDF files get encrypted and decrypted no problems, but text files I don't know it's not showing anything in the file after decryption.
private void encrypt (string input, string output, string strHash )
{
FileStream inStream, outStream;
CryptoStream CryStream;
TripleDESCryptoServiceProvider TDC = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteTexto;
inStream = new FileStream(input, FileMode.Open, FileAccess.Read);
outStream = new FileStream(output, FileMode.OpenOrCreate, FileAccess.Write);
byteHash = md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strHash));
byteTexto = File.ReadAllBytes(input);
md5.Clear();enter code here
TDC.Key = byteHash;
TDC.Mode = CipherMode.ECB;
CryStream = new CryptoStream(outStream, TDC.CreateEncryptor(), CryptoStreamMode.Write);
int bytesRead;
long length, position = 0;
length = inStream.Length;
while(position < length)
{
bytesRead = inStream.Read(byteTexto, 0, byteTexto.Length);
position += bytesRead;
CryStream.Write(byteTexto, 0, bytesRead);
}
inStream.Close();
outStream.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.ShowDialog();
txtLocalDecFile.Text = open.FileName;
SaveFileDialog save = new SaveFileDialog();
save.ShowDialog();
txtNewDecFile.Text = save.FileName;
decrypt(txtLocalDecFile.Text, txtNewDecFile.Text, key);
}
private void decrypt(string input, string output, string strHash)
{
FileStream inStream, outStream;
CryptoStream CryStream;
TripleDESCryptoServiceProvider TDC = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteTexto;
inStream = new FileStream(input, FileMode.Open, FileAccess.Read);
outStream = 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;
CryStream = new CryptoStream(outStream, TDC.CreateDecryptor(), CryptoStreamMode.Write);
int bytesRead;
long length, position = 0;
length = inStream.Length;
while (position < length)
{
bytesRead = inStream.Read(byteTexto, 0, byteTexto.Length);
position += bytesRead;
CryStream.Write(byteTexto, 0, bytesRead);
}
inStream.Close();
outStream.Close();
}

You forgot to close your CryptoStream which means that it could not flush all data to the file.
Either close the stream like you do with inStream and outStream or call FlushFinalBlock() on CryStream.
There is an example in the documentation.

Try use AES encryption:
http://www.codeproject.com/Articles/769741/Csharp-AES-bits-Encryption-Library-with-Salt
There is an example of how to encrypt and decrypt

Related

Padding is invalid when decrypt file

static SymmetricAlgorithm encryption;
static string password = "SBC";
static string salt = "ash";
public Decryption()
{
encryption = new RijndaelManaged();
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(salt));
encryption.Key = key.GetBytes(encryption.KeySize / 8);
encryption.IV = key.GetBytes(encryption.BlockSize / 8);
encryption.Padding = PaddingMode.PKCS7;
}
public void Decrypt(Stream inStream, Stream OutStream)
{
ICryptoTransform encryptor = encryption.CreateDecryptor();
inStream.Position = 0;
CryptoStream encryptStream1 = new CryptoStream(OutStream, encryptor, CryptoStreamMode.Write);
CopyTo(inStream, encryptStream1);
encryptStream1.FlushFinalBlock();
encryptStream1.Close();
inStream.Close();
OutStream.Close();
}
public void CopyTo(Stream input, Stream output)
{
// This method exists only in .NET 4 and higher
byte[] buffer = new byte[4 * 1024];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytesRead);
}
}
In my windows form load i just create a thread and call the function to decrypt file, this is thread function
Thread objthreadhtml = new Thread(new ThreadStart(JsHtmlDecrypt));
objthreadhtml.IsBackground = true;
objthreadhtml.Name = "HtmlJsDecrypt";
objthreadhtml.Priority = ThreadPriority.Highest;
objthreadhtml.Start();
below function is decrypt function
public static void JsHtmlDecrypt()
{
string startPathForHtml = Application.LocalUserAppDataPath.Replace("\\OfflineApplication\\OfflineApplication\\1.0.0.0", "").ToString() + "\\Apps\\Html\\";
var directoryPathForHtml = new DirectoryInfo(startPathForHtml);
foreach (FileInfo fileForHtml in directoryPathForHtml.GetFiles())
{
FileStream inFsForHtml = fileForHtml.OpenRead();
FileInfo inforFHtml = new FileInfo(fileForHtml.FullName.Replace(fileForHtml.Extension, ".html"));
FileStream outFsForHtml = inforFHtml.Create();
UnZipDecryptionEncryption.Decryption m_decryption1 = new Decryption();
m_decryption1.Decrypt(inFsForHtml, outFsForHtml);
inFsForHtml.Close();
outFsForHtml.Close();
UnZipDecryptionEncryption.DeleteZipandFiles m_delete1 = new DeleteZipandFiles();
m_delete1.DeleteFiles(fileForHtml.FullName);
}
}
Here i get the error padding is invalid in the line
encryptStream1.FlushFinalBlock();
Please help me someone how to solve this i am stuck in it.
Your "decrypt" function is trying to do the opposite of what you want: encrypt the data:
CryptoStream encryptStream1 = new CryptoStream(OutStream, encryptor, CryptoStreamMode.Write);
What you want, I assume, is to decrypt it (my code uses byte arrays as input/output, so you may want to modify that):
ICryptoTransform decryptor = encryption.CreateDecryptor();
// byte[] (cipherText) <-- encryted text
MemoryStream memoryStream = new MemoryStream(cipherText);
// here is the most important part: CryptoStreamMode.Read
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherText.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
// my text uses UTF8 encoding, so to get the plain text as string:
string result = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);

Cant access the file because its being used in another process do I multi-thread?

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}");
}

Open encrypted image as Bitmap C#

I need to perform data hiding in encrypted image. To perform data hiding i need to have bitmap Image. But i don't know how to save the image as bitmap.
Below is my encryption code.
public void EncryptFile(string source, string destination)
{
string sKey = "super545";
FileStream fsInput = new FileStream(source, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted = new FileStream(destination, 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);
byte[] bytearrayinput = new byte[fsInput.Length - 1];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}
This is called like:
EncryptFile(originalimage, output);
output is a string variable with the path to store the encrypted image.
How can I call the function to run the encryption?
I receive the error the parameter is invalid when i hit this line:
Bitmap bitmap3 = new Bitmap(output);
I guess what you are trying to do is pretty close to this:
public void EncryptFile(string source, string destination)
{
string sKey = "super545";
FileStream fsInput = new FileStream(source, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted = new FileStream(destination, FileMode.Create, FileAccess.Write);
//Consider to use something else, DES is dead
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//use some key derivation function like pbkdf2 instead
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
//should be random, may be fixed ONLY for testing purposes
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);
//byte[] bytearrayinput = new byte[fsInput.Length - 1]; // what do you need that big buffer for anyways?
//fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
//cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
byte[] headerBuffer = new byte[54]; // buffer for our bmp header ... without any color tables or masks
//No need for lots of checks in a proof of concept
fsInput.Read(headerBuffer, 0, headerBuffer.Length);
var biCompression = BitConverter.ToInt32(headerBuffer, 30); //get biComp from header
if (biCompression != 0 && biCompression != 3)
{
throw new Exception("Compression is not in the correct format");
}
//The buffer is copied without any encryption
fsEncrypted.Write(headerBuffer, 0, headerBuffer.Length);
//copy the rest and encrypt it ... don't care about color tables and masks for now
//and let's just hope plaintext and ciphertext have the right size
fsInput.CopyTo(cryptostream);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}

C# DES File Decryption Breaking Non-Text Files

I have these two methods which are pretty much copy+pastes from http://support.microsoft.com/kb/307010.
When I decrypt the files, if they are any type of text file such as .txt, .xml, .html, etc. I can open them up and everything is fine. Any type of file not just text, such as .exe, .jpg, .pdf, etc. all break when decrypted. Is there anything I am doing wrong? Are these methods using binary to encrypt/decrypt the files? If not is there a way I can make it binary?
Any help is greatly appreciated!
public 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);
byte[] bytearrayinput = new byte[fsInput.Length];
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsInput.Close();
fsEncrypted.Close();
}
public static void DecryptFile(string sInputFilename,
string sOutputFilename,
string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
//A 64 bit key and IV is required for this provider.
//Set secret key For DES algorithm.
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
//Set initialization vector.
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
//Create a file stream to read the encrypted file back.
FileStream fsread = new FileStream(sInputFilename,
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(fsread,
desdecrypt,
CryptoStreamMode.Read);
//Print the contents of the decrypted file.
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
fsread.Close();
cryptostreamDecr.Close();
}
I don't know what the guy that wrote that article was smoking, but:
DESCryptoServiceProvider desCrypto =
(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();
return ASCIIEncoding.ASCII.GetString(desCrypto.Key);
will not get you a valid key. At least one problem is the fact that the key you use to encrypt is not the same key that you're using to decrypt, because you can't convert bytes to ASCII and back like that.
If you want to treat the key as a string, what you probably want is:
string keyAsString = Convert.ToBase64String(desCrypto.Key);
Then when you want to turn it back into bytes, instead of ASCIIEncoding.ASCII.GetBytes, you'll do:
byte[] key = Convert.FromBase64String(keyAsString);
EDIT
There's a ton more wrong with that article too. I'd say ignore that one and find a better example.
EDIT
Here's a very clean basic AES working example that I use for my standard encryption needs. Some of the major improvements over the article are:
Proper creation of a key
Current algorithm (AES 256-bit key)
Random IV
Buffered file access instead of reading/writing the entire file in one chunk
Wrapping all the disposable objects in using
Aside from that, it's the same basic idea.
using System;
using System.IO;
using System.Security.Cryptography;
namespace ConsoleApplication12
{
class Program
{
private const int KEY_SIZE_BYTES = 32;
private const int IV_SIZE_BYTES = 16;
static void Main(string[] args)
{
var rand = new Random();
using (var fs = File.Open(#"C:\temp\input.bin", FileMode.Create, FileAccess.Write, FileShare.None))
{
byte[] buffer = new byte[10000];
for (int i = 0; i < 100; ++i)
{
rand.NextBytes(buffer);
fs.Write(buffer, 0, buffer.Length);
}
}
string key = GenerateRandomKey();
Encrypt(#"C:\temp\input.bin", #"C:\temp\encrypted.bin", key);
Decrypt(#"C:\temp\encrypted.bin", #"C:\temp\decyrypted.bin", key);
}
static string GenerateRandomKey()
{
byte[] key = new byte[KEY_SIZE_BYTES];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(key);
}
return Convert.ToBase64String(key);
}
static void Encrypt(string inputFile, string outputFile, string key)
{
const int BUFFER_SIZE = 8192;
byte[] buffer = new byte[BUFFER_SIZE];
byte[] keyBytes = Convert.FromBase64String(key);
byte[] ivBytes = new byte[IV_SIZE_BYTES];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(ivBytes);
}
using (var inputStream = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var outputStream = File.Open(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
outputStream.Write(ivBytes, 0, ivBytes.Length);
using (var cryptoAlgo = Aes.Create())
{
using (var encryptor = cryptoAlgo.CreateEncryptor(keyBytes, ivBytes))
{
using (var cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
{
int count;
while ((count = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
cryptoStream.Write(buffer, 0, count);
}
}
}
}
}
}
}
static void Decrypt(string inputFile, string outputFile, string key)
{
const int BUFFER_SIZE = 8192;
byte[] buffer = new byte[BUFFER_SIZE];
byte[] keyBytes = Convert.FromBase64String(key);
byte[] ivBytes = new byte[IV_SIZE_BYTES];
using (var inputStream = File.Open(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
inputStream.Read(ivBytes, 0, ivBytes.Length);
using (var outputStream = File.Open(outputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var cryptoAlgo = Aes.Create())
{
using (var decryptor = cryptoAlgo.CreateDecryptor(keyBytes, ivBytes))
{
using (var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
{
int count;
while ((count = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, count);
}
}
}
}
}
}
}
}
}
Because the IV is random, you'll see another small difference in technique. When encrypting the file, you first write the IV to the encrypted file (it's not a secret, so you just write it straight out). When decrypting the file, you read the first few bytes to retrieve the IV, then the rest of the file contains the actual encrypted data. The purpose of a random IV is so the same plaintext file will encrypt into a different encrypted file every time you run it.
The Main method here demonstrates encryption with a random key. If you want to use a password, it's a little more work, but you can implement PBKDF2 with maybe a dozen or so extra lines of code.

Retrieving Encrypted Rich Text file and showing it in a RichTextBox

OK, my need here is to save whatever typed in the rich text box to a file, encrypted, and also retrieve the text from the file again and show it back on the rich textbox. Here is my save code.
private void cmdSave_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.GenerateIV();
aes.GenerateKey();
aes.Mode = CipherMode.CBC;
TextWriter twKey = new StreamWriter("key");
twKey.Write(ASCIIEncoding.ASCII.GetString(aes.Key));
twKey.Close();
TextWriter twIV = new StreamWriter("IV");
twIV.Write(ASCIIEncoding.ASCII.GetString(aes.IV));
twIV.Close();
ICryptoTransform aesEncrypt = aes.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(fs, aesEncrypt, CryptoStreamMode.Write);
richTextBox1.SaveFile(cryptoStream, RichTextBoxStreamType.RichText);
}
I know the security consequences of saving the key and iv in a file but this just for testing :)
Well, the saving part works fine which means no exceptions... The file is created in filePath and the key and IV files are created fine too...
OK now for retrieving part where I am stuck :S
private void cmdOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.ShowDialog();
FileStream openRTF = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
TextReader trKey = new StreamReader("key");
byte[] AesKey = ASCIIEncoding.ASCII.GetBytes(trKey.ReadLine());
TextReader trIV = new StreamReader("IV");
byte[] AesIV = ASCIIEncoding.ASCII.GetBytes(trIV.ReadLine());
aes.Key = AesKey;
aes.IV = AesIV;
ICryptoTransform aesDecrypt = aes.CreateDecryptor();
CryptoStream cryptoStream = new CryptoStream(openRTF, aesDecrypt, CryptoStreamMode.Read);
StreamReader fx = new StreamReader(cryptoStream);
richTextBox1.Rtf = fx.ReadToEnd();
//richTextBox1.LoadFile(fx.BaseStream, RichTextBoxStreamType.RichText);
}
But the richTextBox1.Rtf = fx.ReadToEnd(); throws an cryptographic exception "Padding is invalid and cannot be removed."
while richTextBox1.LoadFile(fx.BaseStream, RichTextBoxStreamType.RichText); throws an NotSupportedException "Stream does not support seeking."
Any suggestions on what i can do to load the data from the encrypted file and show it in the rich text box?
Your IV and Key are never written in the file to begin with (judging from your save_cmd)
And same goes for your opening. There's no link at ALL between between your ("Key" stream and your file anywhere...)
Updated :
Here is a better version of your code :
private void button1_Click(object sender, EventArgs e)
{
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.GenerateIV();
aes.GenerateKey();
aes.Mode = CipherMode.CBC;
File.WriteAllBytes("Key",aes.Key);
File.WriteAllBytes("IV",aes.IV);
ICryptoTransform aesEncrypt = aes.CreateEncryptor();
using (FileStream fs = new FileStream("file.crypt", FileMode.Create, FileAccess.Write))
{
using (CryptoStream cryptoStream = new CryptoStream(fs, aesEncrypt, CryptoStreamMode.Write))
{
richTextBox1.SaveFile(cryptoStream, RichTextBoxStreamType.RichText);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.ShowDialog();
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
byte[] AesKey = File.ReadAllBytes("Key");
byte[] AesIV = File.ReadAllBytes("IV");
aes.Key = AesKey;
aes.IV = AesIV;
ICryptoTransform aesDecrypt = aes.CreateDecryptor();
using (FileStream openRTF = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read))
{
using (CryptoStream cryptoStream = new CryptoStream(openRTF, aesDecrypt, CryptoStreamMode.Read))
{
using (StreamReader fx = new StreamReader(cryptoStream))
{
richTextBox1.Rtf = fx.ReadToEnd();
}
}
}
}
It works.
Since you never closed the CryptoStream in Save, it never called FlushFinalBlock to finish writing the data. Therefore, not all of the data was saved.
OK, i achieved perfectly what i wanted to achieve. There were several key failures in my code...
First, thanx to SLaks and Jipy i figured out that "thou shall close all streams that were open" :)
And the second major blunder i did was trying to save the key and iv in a file where actually saving or loading it back did not work! Thus i just had two byte[] to save the key and IV
I changed the padding scheme to ISO10126 and made sure that the Mode was CBC when both opening and closing commands.
And else i had to do was add the code to open command and it worked :) :) :)
StreamReader fx = new StreamReader(cryptoStream);
fx.Read(fileContent, 0, Convert.ToInt32(fileContent.Length));
fx.Close();
cryptoStream.Close();
richTextBox1.Rtf = new String(fileContent);
Anyway any other stupid performance issues are welcome :)
Here is the complete open and close commands to anyone who is interested.
byte[] globalKey = new byte[32];
byte[] globalIV = new byte[16];
private void cmdSave_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.GenerateIV();
aes.GenerateKey();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.ISO10126;
globalKey = aes.Key;
globalIV = aes.IV;
ICryptoTransform aesEncrypt = aes.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(fs, aesEncrypt, CryptoStreamMode.Write);
richTextBox1.SaveFile(cryptoStream, RichTextBoxStreamType.RichText);
cryptoStream.Close();
fs.Close();
richTextBox1.Clear();
}
private void cmdOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
openFile.ShowDialog();
FileStream openRTF = new FileStream(openFile.FileName, FileMode.Open, FileAccess.Read);
AesCryptoServiceProvider aes = new AesCryptoServiceProvider();
aes.Key = globalKey;
aes.IV = globalIV;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.ISO10126;
ICryptoTransform aesDecrypt = aes.CreateDecryptor();
CryptoStream cryptoStream = new CryptoStream(openRTF, aesDecrypt, CryptoStreamMode.Read);
FileInfo fileNFO = new FileInfo(openFile.FileName);
char[] fileContent = new char[fileNFO.Length];
StreamReader fx = new StreamReader(cryptoStream);
fx.Read(fileContent, 0, Convert.ToInt32(fileContent.Length));
fx.Close();
cryptoStream.Close();
richTextBox1.Rtf = new String(fileContent);
}

Categories