Reputation: 644
I've got a weird issue while trying to decrypt an encrypted text file. Basically the contents of the .txt file is "this is a test :)" , when decrypting the output is "this is a test :", spot the missing ")".
This isn't the case when I decrypt the file a byte at a time (while loop), but when using the code bellow it seems to have the above issue.
private static void DecryptFile(string inputFile, string outputFile, string skey)
{
RijndaelManaged aes = new RijndaelManaged();
try
{
byte[] key = ASCIIEncoding.UTF8.GetBytes(skey);
byte[] file = File.ReadAllBytes(inputFile);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(key, key), CryptoStreamMode.Write))
{
cs.Write(file, 0, file.Length);
File.WriteAllBytes(outputFile, ms.ToArray());
aes.Clear();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
aes.Clear();
}
}
Please excuse the sloppy code, it was merely for testing purposes.
Upvotes: 1
Views: 938
Reputation: 34408
A block-cipher CryptoStream can only encrypt or decrypt content in fixed block sizes. You haven't given it enough content to fill the final block so it's waiting for more. This partial incomplete block is getting lost.
You either need to call FlushFinalBlock on your CryptoStream or fall outside the using
so that it automatically closes it. Then your MemoryStream should contain the missing characters.
Note that when decrypting your output will now be rounded up to a full block, i.e. you'll get extra zeros padding the end of your data.
Upvotes: 3