I am receiving the following error message when attempting to decrypt text:
"length of the data to decrypt is invalid"
this occurs when I either attempt to flush or close my Cryptostream (I am using a memory stream to store the decrypted text)
here is the encrypt/decrypt methods:
using System.Security.Cryptography;
.
.
.
///
/// Encrypts text.
///
///
Text to incrypt.
///
Encrypted text.
public static string Encrypt(string textToEncrypt)
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.IV = new byte[8];
PasswordDeriveBytes pdb = new PasswordDeriveBytes(key, new byte[0]);
des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
MemoryStream ms = new MemoryStream((textToEncrypt.Length * 2)-1);
CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(),CryptoStreamMode.Write);
byte[] plainBytes = Encoding.UTF8.GetBytes(textToEncrypt);
encStream.Write(plainBytes, 0, plainBytes.Length);
encStream.FlushFinalBlock();
byte[] encryptedBytes = new byte[ms.Length];
ms.Position = 0;
ms.Read(encryptedBytes, 0, (int)ms.Length);
encStream.Close();
return Convert.ToBase64String(encryptedBytes);
}
///
/// Decrypts an encrypted text.
///
///
Text to decrypt.
///
Decrypted text.
public static string Decrypt(string textToDecrypt)
{
string rtn;
try
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.IV = new byte[8];
PasswordDeriveBytes pdb = new PasswordDeriveBytes(key, new byte[0]);
des.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
byte[] encryptedBytes = Convert.FromBase64String(textToDecrypt);
MemoryStream ms = new MemoryStream((textToDecrypt.Length*2));
CryptoStream decStream = new CryptoStream(ms, des.CreateDecryptor(),CryptoStreamMode.Write);
decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
decStream.FlushFinalBlock();
byte[] plainBytes = new byte[ms.Length];
ms.Position = 0;
ms.Read(plainBytes, 0, (int)ms.Length);
decStream.Close();
rtn = Encoding.UTF8.GetString(plainBytes);
}
catch (Exception ex)
{
rtn = ex.Message;
}
finally
{
}
return rtn;
}
this was written for me by a contractor who is no longer with us... any help would be GREATLY appreciated!