AesCryptoServiceProvider decrypt

1.7k views Asked by At

I am attempting to decrypt using this function but I am unsure what is causing it to fail

  public string Decrypt(byte[] cipherText, byte[] IV, byte[] key)
    {

        using (AesCryptoServiceProvider AESDecrypt = new AesCryptoServiceProvider())
        {

            //here we set the key and IV instead having the class generate them.
            AESDecrypt.IV = IV;
            AESDecrypt.Key = key;

            ICryptoTransform decryptor = AESDecrypt.CreateDecryptor(AESDecrypt.Key, 
                                 AESDecrypt.IV);

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, 
                     decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        csDecrypt.Flush();
                        plainText = srDecrypt.ReadToEnd();
                        return plainText;
                    }
                }
            }
       }

    }

The plainText returns an empty string. The key and IV are system generated in a previous function and are being passed correctly.

1

There are 1 answers

0
Anthony On BEST ANSWER

I misread the first question's answer and used a .flushfinalblock to get it to return "a ciphertext" without really addressing the underlying issue. When I moved the cipher = msEncrypt.ToArray(); outside of the crypto stream it worked perfectly. And removed the .flush(). .FacePalm()