Reputation: 10448
While decrypting a string I am getting length of the data to decrypt is invalid error when i call FlushFinalBlock function
key = Encoding.UTF8.GetBytes(stringKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] byteArray = Convert.FromBase64String(text);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cryptoStream.Write(byteArray, 0, byteArray.Length);
cryptoStream.FlushFinalBlock();
return Encoding.UTF8.GetString(memoryStream.ToArray());
what is the issue and how to resolve it?
Upvotes: 1
Views: 10919
Reputation: 1038780
You didn't show how is the string encrypted, whether you are using the same keys and IV, etc... Here's a full working example you could adapt to your scenario:
class Program
{
private static byte[] DESKey = { 200, 5, 78, 232, 9, 6, 0, 4 };
private static byte[] DESInitializationVector = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
static void Main()
{
var encrypted = Encrypt("foo bar");
Console.WriteLine(encrypted);
var decrypted = Decrypt(encrypted);
Console.WriteLine(decrypted);
}
public static string Encrypt(string value)
{
using (var cryptoProvider = new DESCryptoServiceProvider())
using (var memoryStream = new MemoryStream())
using (var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(DESKey, DESInitializationVector), CryptoStreamMode.Write))
using (var writer = new StreamWriter(cryptoStream))
{
writer.Write(value);
writer.Flush();
cryptoStream.FlushFinalBlock();
writer.Flush();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
}
public static string Decrypt(string value)
{
using(var cryptoProvider = new DESCryptoServiceProvider())
using(var memoryStream = new MemoryStream(Convert.FromBase64String(value)))
using(var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(DESKey, DESInitializationVector), CryptoStreamMode.Read))
using(var reader = new StreamReader(cryptoStream))
{
return reader.ReadToEnd();
}
}
}
Upvotes: 2