I'm trying to encrypt a tif file using RijndaelManaged. Initially I was getting "Padding is invalid and cannot be removed" error. Got that fixed by adding FlushFinalBlock() to my Encryption method. Now, however, when I try to decrypt a file that has been encrypted in a different application (they both use the same class to encrypt and decrypt) I'm getting an error "Length of data to decrypt is invalid".
The code below is from a class that is compiled into a library that both applications use.
In both the Decrypt and Encrypt methods below, the parameter arg is the .tif file. Maybe I should be using a different Mode or Padding than the default. Sure would appreciate some help.
TIA, edepperson
private byte[] DecryptRijndaelManaged(string inputkey, string saltval, byte[] arg)
{
byte[] earg = null;
initializeRJ(inputkey, saltval);
ICryptoTransform decryptor = alg.CreateDecryptor();
CryptoStream decryptstream = null;
using (MemoryStream ms = new MemoryStream(arg))
{
int argL = arg.Length;
earg = new byte[argL];
try
{
decryptstream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
ms.Seek(0, SeekOrigin.Begin);
decryptstream.Read(earg, 0, earg.Length);
}
finally
{
decryptstream.Close();
ms.Close();
}
}
return earg;
}
private byte[] EncryptRijndaelManaged(string inputkey, string saltval, byte[] arg)
{
byte[] earg = null;
initializeRJ(inputkey, saltval);
using (MemoryStream ms = new MemoryStream())
{
ICryptoTransform encryptor = alg.CreateEncryptor();
using (CryptoStream encryptstream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
encryptstream.Write(arg, 0, arg.Length);
encryptstream.FlushFinalBlock();
int argL = (int)ms.Length;
ms.Seek(0, SeekOrigin.Begin);
earg = new byte[argL];
ms.Read(earg, 0, argL);
ms.Flush();
encryptstream.Close();
}
ms.Close();
}
return earg;
}
private void initializeRJ(string inputkey, string saltval)
{
alg = new RijndaelManaged();
string pwd = inputkey;
byte[] salt = Encoding.ASCII.GetBytes(saltval);
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(pwd, salt);
alg.Key = key.GetBytes(alg.KeySize / 8);
alg.IV = key.GetBytes(alg.BlockSize / 8);
}