Unchecked returned value causing unexpected states and conditions

1.8k views Asked by At

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);
    }
1

There are 1 answers

0
John Saunders On

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?