I have problems with the code below. I have a file in a temporary place that needs encryption, this function encrypts the data, which is then stored in the location "pathToSave".
When checking, the whole file does not seem to be processed properly. There are no bits in my release, and I suspect that it has something to do with a while loop that does not go through the entire stream.
Aside, if I try to call CryptStrm.Close () after a while loop, I get an exception. This means that if I try to decrypt the file, I get a file already using the error!
I tried everything ordinary and Ive looked at similar problems here, any help would be great.
thanks
public void EncryptFile(String tempPath, String pathToSave) { try { FileStream InputFile = new FileStream(tempPath, FileMode.Open, FileAccess.Read); FileStream OutputFile = new FileStream(pathToSave, FileMode.Create, FileAccess.Write); RijndaelManaged RijCrypto = new RijndaelManaged(); //Key byte[] Key = new byte[32] { ... }; //Initialisation Vector byte[] IV = new byte[32] { ... }; RijCrypto.Padding = PaddingMode.None; RijCrypto.KeySize = 256; RijCrypto.BlockSize = 256; RijCrypto.Key = Key; RijCrypto.IV = IV; ICryptoTransform Encryptor = RijCrypto.CreateEncryptor(Key, IV); CryptoStream CryptStrm = new CryptoStream(OutputFile, Encryptor, CryptoStreamMode.Write); int data; while (-1 != (data = InputFile.ReadByte())) { CryptStrm.WriteByte((byte)data); } } catch (Exception EncEx) { throw new Exception("Encoding Error: " + EncEx.Message); } }
EDIT:
I made the assumption that my problem is with encryption. My decryption may be the culprit
public String DecryptFile(String encryptedFilePath) { FileStream InputFile = new FileStream(encryptedFilePath, FileMode.Open, FileAccess.Read); RijndaelManaged RijCrypto = new RijndaelManaged(); //Key byte[] Key = new byte[32] { ... }; //Initialisation Vector byte[] IV = new byte[32] { ... }; RijCrypto.Padding = PaddingMode.None; RijCrypto.KeySize = 256; RijCrypto.BlockSize = 256; RijCrypto.Key = Key; RijCrypto.IV = IV; ICryptoTransform Decryptor = RijCrypto.CreateDecryptor(Key, IV); CryptoStream CryptStrm = new CryptoStream(InputFile, Decryptor, CryptoStreamMode.Read); String OutputFilePath = Path.GetTempPath() + "myfile.name"; StreamWriter OutputFile = new StreamWriter(OutputFilePath); OutputFile.Write(new StreamReader(CryptStrm).ReadToEnd()); CryptStrm.Close(); OutputFile.Close(); return OutputFilePath; }