1

I am doing an Aes decryption but I am keep getting an exception "Padding is invalid and cannot be removed". The encrypted message given to me as response from the server which I am trying to decrypt. This is the function I am using to decrypt the code

Any ideas?

public async static Task<string> DecriptResponse(string data)
    {
        try
        {
            byte[] decodedData = Convert.FromBase64String(data);
            using (Aes aesAlg = new AesManaged())
            {
                aesAlg.Key = Encoding.UTF8.GetBytes(Constants.DecryptionKey);
                aesAlg.IV = Encoding.UTF8.GetBytes(Constants.DecryptionIv);

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(decodedData))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            string plaintext = srDecrypt.ReadToEnd();
                            Debug.WriteLine(plaintext);
                            return plaintext;
                        }
                    }
                }

            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            return "";
        }
        return "";
    }
Vishnu S
  • 23
  • 1
  • 7
  • 1
    I'd say it's because the padding is invalid and can't be removed. Also, having a constant IV makes your code insecure. – Luke Joshua Park Jan 30 '17 at 20:30
  • If your input is 16 bytes: the IV is wrong or key is wrong or encrypt and decrypt use different padding. If your input is more than 16 bytes: the key is wrong or encrypt and decrypt use different padding. Decrypting with `aesAlg.Padding = PaddingMode.None` (before `CreateDecryptor`) will help you see what the raw decryption result was. If that's nonsense, the key is wrong. If only the end is weird: you have mismatched padding. – bartonjs Jan 31 '17 at 00:10
  • When I use aesAlg.Padding its gives me an error "Aes does not contain definition for Padding ... ". Have any idea? – Vishnu S Jan 31 '17 at 05:26
  • 1
    Possible duplicate of [Padding is invalid and cannot be removed?](http://stackoverflow.com/questions/8583112/padding-is-invalid-and-cannot-be-removed) – Cee McSharpface May 03 '17 at 18:34

0 Answers0