-1

I have been searching the internet for over an hour and can only find client side discussions the my latest scan finding. What I am receiving is method that uses the Read() method and because the Read() ignores the value returned could cause the program to overlook unexpected states and conditions finding. If anyone can explain, in small detail, and possibility recommend a fix the would be great. The function is below:

Offending line of code in the method:

csEncrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

Calling method:

    public String DecryptMessage(byte[] encrypted)
    {
        ASCIIEncoding textConverter = new ASCIIEncoding();
        decryptor = aes.CreateDecryptor(key, IV);
        MemoryStream msDecrypt = new MemoryStream(encrypted);
        csEncrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
        byte[] fromEncrypt = new byte[encrypted.Length];
        csEncrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
        return textConverter.GetString(fromEncrypt);
    }
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Steve Holdorf
  • 141
  • 1
  • 14
  • Might have something to do with the `MemoryStream` not being in a `using` block. And, are you certain that your error logging works? If you add `throw new Exception("Testing!");` at the start of that method, does the exception get logged? If not, then there could be a problem you know nothing about. – John Saunders Jun 10 '15 at 17:40
  • It could also be because you are ignoring the return value from `Read`. – John Saunders Jun 11 '15 at 20:31

1 Answers1

0

Try not ignoring the return value:

public String DecryptMessage(byte[] encrypted)
{
    ASCIIEncoding textConverter = new ASCIIEncoding();
    decryptor = aes.CreateDecryptor(key, IV);
    using (MemoryStream msDecrypt = new MemoryStream(encrypted))
    {
        using (var csEncrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
        {
            byte[] fromEncrypt = new byte[encrypted.Length];
            var bytesRead = csEncrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
            return textConverter.GetString(fromEncrypt, 0, bytesRead);
        }
    }
}

What would happen in your code if fewer bytes were returned than you expected?

John Saunders
  • 160,644
  • 26
  • 247
  • 397