I am getting error "the input data is not a complete block" in decryption using AES/CBC/Pkcs7 algorithm in C#

257 views Asked by At
public static string Decryptss(string cipherText, string symkey)
{
    try
    {
        return DecryptStringFromBytes_Aes(Convert.FromBase64String(cipherText), Encoding.UTF8.GetBytes(symkey), new byte[16]);
    }
    catch (CryptographicException ex)
    {
        if (ex.Message == "The input data is not a complete block.")
        {
            // This is plaintext
            return cipherText;
        }
        else
        {
            return "";
        }
    }
    catch (FormatException ex)
    {
        if (ex.Message == "Invalid length for a Base-64 char array or string." || ex.Message.StartsWith("The input is not a valid Base-64 string"))
        {
            // This is plaintext
            return cipherText;
        }
        else
        {
            return "";
        }
    }
}

public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
    // Check arguments.
    if (cipherText == null || cipherText.Length <= 0)
        throw new ArgumentNullException("cipherText");
    if (Key == null || Key.Length <= 0)
        throw new ArgumentNullException("Key");
    if (IV == null || IV.Length <= 0)
        throw new ArgumentNullException("IV");

    // Declare the string used to hold
    // the decrypted text.
    string plaintext = null;

    // Create an Aes object
    // with the specified key and IV.
    using (Aes aesAlg = Aes.Create())
    {
        aesAlg.Key = Key;
        aesAlg.IV = IV;

        // 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(cipherText))
        {
            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.
                    // Here I am Getting Error.
                    plaintext = srDecrypt.ReadToEnd();
                }
            }
        }

    }

    return plaintext;
}

I was tried with different - different methods. But that is not work for me.

0

There are 0 answers