1

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.

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
Anthony
  • 913
  • 3
  • 23
  • 32
  • 1
    When you open your `StreamReader`, is msDecrypt / cipherText the lengths you expect them to be? I only do this stuff with streams rather than `byte[]`s - but have you tried checking the position of the msDecrypt stream (when you open the stream reader?). It needs to be at position 0. – ne1410s Dec 13 '14 at 14:47
  • 1
    Are you flushing in the encrypt method? Check the length of the ciphertext at the beginning of your method and throw an exception if it is zero. Using the encryption code you had in the previous thread, if you didn't implement the Flush() properly, you might have a zero length byte array. – John Koerner Dec 13 '14 at 14:57
  • 1
    Please remove the flush, see if it works. If you just have 16 bytes of ciphertext, it may be that the plaintext itself consists of 0 bytes (or, if you just print it out, out of unprintable characters). In that case you just have a block of 16 padding bytes. – Maarten Bodewes Dec 13 '14 at 15:16

1 Answers1

0

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()

Anthony
  • 913
  • 3
  • 23
  • 32