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);
}
Related
I've been fighting with chained using statements, and am unable to resolve the latest in a long line of implementation issues. I need to compress, then encrypt and append the generated IV to the selected file. This all appears to work correctly, however i'm unable to unwind the process. After looking at several similar stack postings and articles i'm still unable to get it to work and am now after more direct assistance.
The latest thrown error is System.IO.InvalidDataException: 'Found invalid data while decoding.' It appears that the decryption stream isn't functioning as intended and that's throwing the decompression stream out of wack.
byte[] key;
byte[] salt;
const int keySize = 256;
const int blockSize = keySize;
byte[] iv = new byte[blockSize / 8];//size to bits
RijndaelManaged rjndl;
RNGCryptoServiceProvider cRng;
void InitializeCryptor() {
//Temporarily define the salt & key
salt = Encoding.UTF8.GetBytes("SaltShouldBeAtLeast8Bytes");
key = new Rfc2898DeriveBytes("MyL0ngPa$$phra$e", salt, 4).GetBytes(keySize / 8);
//Initialize the crypto RNG generator
cRng = new RNGCryptoServiceProvider();
// Create instance of Rijndael (AES) for symetric encryption of the data.
rjndl = new RijndaelManaged();
rjndl.KeySize = keySize;
rjndl.BlockSize = blockSize;
rjndl.Mode = CipherMode.CBC;
}
void CompressAndEncryptFile(string relativeFilePath, string fileName) {
//Create a unique IV each time
cRng.GetBytes(iv);
//Create encryptor
rjndl.Key = key;
rjndl.IV = iv;
ICryptoTransform encryptor = rjndl.CreateEncryptor(rjndl.Key, rjndl.IV);
//Create file specific output sub-directory
Directory.CreateDirectory(Path.Combine(outputPath, relativeFilePath));
//Read and compress file into memory stream
using (FileStream readStream = File.OpenRead(Path.Combine(initialpath, relativeFilePath, fileName)))
using (FileStream writeStream = new FileStream(Path.Combine(outputPath, relativeFilePath, fileName + ".dat"), FileMode.Create))
using (CryptoStream encryptStream = new CryptoStream(writeStream, encryptor, CryptoStreamMode.Write))
using (DeflateStream compStream = new DeflateStream(encryptStream, CompressionLevel.Optimal)) {
//Write the following to the FileStream for the encrypted file:
// - length of the IV
// - the IV
byte[] ivSize = BitConverter.GetBytes(rjndl.IV.Length);
writeStream.Write(ivSize, 0, 4);
writeStream.Write(rjndl.IV, 0, rjndl.BlockSize / 8);
readStream.CopyTo(compStream);
}
}
void DecryptAndDecompressFile(string relativeFilePath) {
string outputPath = Path.Combine(initialpath, "Unpack");
Directory.CreateDirectory(outputPath);
using (FileStream readStream = new FileStream(Path.Combine(initialpath, manifestData.version, relativeFilePath + ".dat"), FileMode.Open)) {
byte[] tmpLength = new byte[4];
//Read length of IV
readStream.Seek(0, SeekOrigin.Begin);
readStream.Read(tmpLength, 0, 3);
int ivLength = BitConverter.ToInt32(tmpLength, 0);
byte[] readIv = new byte[ivLength];
//Read IV
readStream.Seek(4, SeekOrigin.Begin);
readStream.Read(readIv, 0, ivLength);
rjndl.IV = readIv;
//Start at beginning of encrypted data
readStream.Seek(4 + ivLength, SeekOrigin.Begin);
//Create decryptor
ICryptoTransform decryptor = rjndl.CreateEncryptor(key, readIv);
using (CryptoStream decryptStream = new CryptoStream(readStream, decryptor, CryptoStreamMode.Read))
using (DeflateStream decompStream = new DeflateStream(decryptStream, CompressionMode.Decompress))
using (FileStream writeStream = new FileStream(Path.Combine(outputPath, relativeFilePath), FileMode.Create)) {
decompStream.CopyTo(writeStream);
}
}
}
For those who like to point to other similar stack questions and vote to close/duplicate without offering support, the following are the threads, and posts I've worked through first, each without success.
https://learn.microsoft.com/en-us/dotnet/standard/security/walkthrough-creating-a-cryptographic-application
https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.rijndaelmanaged?redirectedfrom=MSDN&view=netcore-3.1
Chained GZipStream/DeflateStream and CryptoStream (AES) breaks when reading
DeflateStream / GZipStream to CryptoStream and vice versa
https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.gzipstream?redirectedfrom=MSDN&view=netcore-3.1#code-snippet-2
How to fix 'Found invalid data while decoding.'
Compression/Decompression string with C#
After ~2 days of investigating, i located my error.
I was calling rjndl.CreateEncryptor instead of rjndl.CreateDecryptor during the decryption portion... (Please tell me this type of $#!t happens to others too)
Once i finish testing i'll update my question code to serve as a nice example for anyone who lands here via google in the future.
I am building a application that can encrypt and decrypt files, in c#. The encryption seems like its working (I think its working) however the decryption gives me the exception "The input data is not a complete block." I have tried almost everything I could find online so I thought I should come here. Here is the decryption code:
static void decryptAES (/*byte[] buffer,*/string filePath,byte[] key, byte[] IV)
{
Console.WriteLine("1");
using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
{
AES.Padding = PaddingMode.PKCS7;
AES.Key = key;
AES.BlockSize = 128;
AES.KeySize = 128;
AES.IV = IV;
using (FileStream fStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
{
using (ICryptoTransform crypt = AES.CreateDecryptor(key, IV))
{
using (CryptoStream crStream = new CryptoStream(fStream, crypt, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(crStream))
{
//breaks here
string data = reader.ReadToEnd();
File.WriteAllText(filePath, data);
File.Move(filePath, filePath.Replace(".encrypted", ""));
}
}
}
}
}
}
It breaks on the line with the comment //breaks here by the way.
Thanks.
Here is the encrypt function
static void encryptAES(byte[] filesBytes,string
filePath,AesCryptoServiceProvider aes)
{
using (FileStream fStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
{
using (ICryptoTransform crypt = aes.CreateEncryptor(aes.Key, aes.IV))
{
using (CryptoStream csStream = new CryptoStream(fStream, crypt, CryptoStreamMode.Write))
{
csStream.Write(filesBytes, 0, filesBytes.Length);
}
try { File.Move(filePath, filePath + ".encrypted"); }
catch (UnauthorizedAccessException)
{
}
}
}
}
And here is the key generation:
static AesCryptoServiceProvider generateAES()
{
AesCryptoServiceProvider a = new AesCryptoServiceProvider();
a.Padding = PaddingMode.PKCS7;
a.BlockSize =128;
a.KeySize = 128;
a.GenerateIV();
a.GenerateKey();
return a;
}
Here is how I stored the IV and AES Key:
private static void dumpKeys(AesCryptoServiceProvider aes)
{
foreach (byte b in aes.Key)
{
Console.Write(b);
}
Console.WriteLine();
foreach (byte b in aes.IV)
{
Console.Write(b);
}
byte[] encryptedKey = encryptRSA(aes.Key);
byte[] encryptedIV = encryptRSA(aes.IV);
Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Keys");
File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Keys\0000000000000.Key", encryptedKey);
File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Keys\1111111111111.IV", encryptedIV);
}
And here is how I retrieve the key and iv data:
byte[] AESKey = decrypt(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Keys\0000000000000.Key");
byte[] AESIV = decrypt(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\Keys\1111111111111.IV");
static byte[] decrypt(string path)
{
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSA.FromXmlString(Properties.Resources.privateKey);
byte[] unencrypted = RSA.Decrypt(File.ReadAllBytes(path), true);
foreach (byte b in unencrypted)
{
Console.Write(b);
}
Console.WriteLine();
return unencrypted;
}
}
Btw I store a public RSA key in my resources file and I use that to decrypt the key.
Thanks
So far, so good. Do you extract the generated Key and IV? I modified your decryption function to an encryption function...
public static void Main()
{
var f = #"q:\test.txt";
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, f, key, iv);
decryptAES(AES, f + ".encrypted", key, iv);
}
static 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);
}
}
}
}
}
static 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);
}
}
}
}
}
Tested it with your code, slightly modified (changed FileMode.Open to FileMode.OpenOrCreate, Added File.Delete before File.Move and merged File.WriteAllText with File.Move) and it works. So a) please review your code. b) If it still fails, provide more details, a single codeblock with every function and a Main-method that calls your functions to reproduce your failure...
static AesCryptoServiceProvider generateAES()
{
AesCryptoServiceProvider a = new AesCryptoServiceProvider();
a.Padding = PaddingMode.PKCS7;
a.BlockSize = 128;
a.KeySize = 128;
a.GenerateIV();
a.GenerateKey();
return a;
}
static void encryptAES(byte[] filesBytes, string filePath, AesCryptoServiceProvider aes)
{
using (FileStream fStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (ICryptoTransform crypt = aes.CreateEncryptor(aes.Key, aes.IV))
{
using (CryptoStream csStream = new CryptoStream(fStream, crypt, CryptoStreamMode.Write))
{
csStream.Write(filesBytes, 0, filesBytes.Length);
}
try {
File.Delete(filePath + ".encrypted");
File.Move(filePath, filePath + ".encrypted");
}
catch (UnauthorizedAccessException)
{
}
}
}
}
static void decryptAES(/*byte[] buffer,*/string filePath, byte[] key, byte[] IV)
{
using (AesCryptoServiceProvider AES = new AesCryptoServiceProvider())
{
AES.Padding = PaddingMode.PKCS7;
AES.Key = key;
AES.BlockSize = 128;
AES.KeySize = 128;
AES.IV = IV;
using (FileStream fStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
{
using (ICryptoTransform crypt = AES.CreateDecryptor(key, IV))
{
using (CryptoStream crStream = new CryptoStream(fStream, crypt, CryptoStreamMode.Read))
{
using (StreamReader reader = new StreamReader(crStream))
{
//breaks here
string data = reader.ReadToEnd();
File.WriteAllText(filePath.Replace(".encrypted", ""), data);
}
}
}
}
}
}
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
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
I'm writing an application to Encrtpt/Decrypt files and using DESCryptoServiceProvider for this purpose. This seems to work for text files but when I use the same application for .xlsx file, the resulting encrypted file and the decrypted file get corrupted and I'm not able to open that any more. is there any way I can encryt / decrypt different kinds of file like .doc..xls etc.
update : added code for encryption/decryption
public static void EncryptFile(string filepath,string fileOutput, string key)
{
FileStream fsInput = new FileStream(filepath, FileMode.Open, FileAccess.Read);
FileStream fsEncrypted = new FileStream(fileOutput, FileMode.Create, FileAccess.Write);
DESCryptoServiceProvider DESc = new DESCryptoServiceProvider();
DESc.Key = ASCIIEncoding.ASCII.GetBytes(key);
DESc.IV = ASCIIEncoding.ASCII.GetBytes(key);
ICryptoTransform desEncrypt = DESc.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();
}
public static void DecryptFile(string filepath, string fileOutput, string key)
{
DESCryptoServiceProvider DESc = new DESCryptoServiceProvider();
DESc.Key = ASCIIEncoding.ASCII.GetBytes(key);
DESc.IV = ASCIIEncoding.ASCII.GetBytes(key);
FileStream fsread = new FileStream(filepath, FileMode.Open, FileAccess.Read);
ICryptoTransform desDecrypt = DESc.CreateDecryptor();
CryptoStream cryptoStreamDcr = new CryptoStream(fsread, desDecrypt, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter(fileOutput);
fsDecrypted.Write(new StreamReader(cryptoStreamDcr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}
static void Main(string[] args)
{
EncryptFile(#"C:\test1.xlsx", #"c:\test2.xlsx", "ABCDEFGH");
DecryptFile(#"C:\test2.xlsx", #"c:\test3.xlsx", "ABCDEFGH");
}
You are not encrypting or decrypting correctly. Encrypt -> Decrypt will always give a file identical to the input. If you post your code we may be able to assist in finding the bug in it.
You should use FileStreama as suggested in one of the comments by Kieren Johnstone. Also, you're not flushing the streams when encrypting - this may not be done automatically, so you should try and flush the streams, too.