Decrypt file into memory

  • Thread starter Thread starter Johny V
  • Start date Start date
J

Johny V

Guest
Hello guys,


So i have function for decrypting my files.


Looks like this:


public static bool FileDecrypt(string inputFile, string outputFile, string password)
{

byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] salt = new byte[32];

FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
fsCrypt.Read(salt, 0, salt.Length);

RijndaelManaged AES = new RijndaelManaged();
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Padding = PaddingMode.PKCS7;
AES.Mode = CipherMode.CFB;

CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);

FileStream fsOut = new FileStream(outputFile, FileMode.Create);

int read;
byte[] buffer = new byte[1048576];

try
{
while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
fsOut.Write(buffer, 0, read);
}
}
catch (CryptographicException ex_CryptographicException)
{
fsOut.Close();
fsCrypt.Close();
LogWriter loger = new LogWriter("Cryptography error: " + ex_CryptographicException.ToString());
return false;
}
catch (Exception ex)
{
fsOut.Close();
fsCrypt.Close();
LogWriter loger = new LogWriter("Exception error: " + ex.ToString());
return false;
}

try
{
cs.Close();
}
catch (Exception ex)
{
fsCrypt.Close();
fsOut.Close();
LogWriter loger = new LogWriter("Error when closing Cryptostream. Error: " + ex.ToString());
return false;
}
finally
{
fsOut.Close();
fsCrypt.Close();
}

return true;


}


And i would like to make function which decrypts the file only into memorystream or returns that memorystream would be more helpfull.

And then i would like to use Xmlserializer on that memorystream. So the file stays encrypted on the harddrive and i still can use the xml configuration from that file.

Is that somehow possible?


Thanks for answers,

Best regards,


John

Continue reading...
 
Back
Top