I'm having some trouble with the code below. I have a file in a temporary location which is in need of encryption, this function encrypts that data which is then stored at the "pathToSave" location.
On inspection is does not seem to be handling the whole file properly - There are bits missing from my output and I suspect it has something to do with the while loop not running through the whole stream.
As an aside, if I try and call CryptStrm.Close() after the while loop I receive an exception. This means that if I attempt to decrypt the file, I get a file already in use error!
Tried all the usual and Ive looked on here at similar issues, 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've made the assumption that my problem is with Encryption. My Decrypt might 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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…