TheAlgorithms/C-Sharp · error · ArgumentException

Invalid padding

Error message

Invalid padding

What it means

After reading the padding length from the last byte, RemovePadding verifies that all trailing padding bytes equal that length, as PKCS#7 requires. If any of them differ, the padding is malformed and the method throws ArgumentException — a strong signal the data is corrupted or was decrypted with the wrong key.

Solutions

  1. Verify keys, IVs, and modes match on both encrypt and decrypt sides.
  2. Add authenticated encryption (HMAC or AES-GCM) to detect corrupted ciphertext.
  3. Check the transport/storage path for truncation or modification.
  4. Confirm padding was added by this same library before removal.

Example fix

// before
var plain = padding.RemovePadding(corruptBytes);
// after
using var aes = Aes.Create(); aes.Mode = CipherMode.GCM; // authenticated
var plain = padding.RemovePadding(gcm.Decrypt(...));
Defensive patterns

Strategy: try-catch

Validate before calling

int len = input[^1];
bool ok = len is >= 1 and <= blockSize && input[^len..].All(b => b == len);
if (!ok) throw new CryptographicException("Corrupted padding detected");

Try / catch

try { plain = padding.RemovePadding(decrypted); }
catch (ArgumentException) { throw new CryptographicException("Decryption failed or data corrupted — check key/IV and integrity"); }

Prevention

When it happens

Trigger: Calling RemovePadding on data whose last `paddingLength` bytes are not all equal to paddingLength — e.g. bit-flipped ciphertext, wrong key/IV producing near-garbage plaintext, data truncated or modified in transit.

Common situations: Man-in-the-middle or transmission corruption; using ECB/CBC with a wrong IV; custom code that overwrote padding bytes; an attacker probing padding oracles.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/67a747910e4d783f. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/Crypto/Paddings/Pkcs7Padding.cs:104

        {
            throw new ArgumentException("Input length must be a multiple of block size");
        }

        // Get the padding length from the last byte of input
        var paddingLength = input[^1];

        // Check if padding length is valid
        if (paddingLength < 1 || paddingLength > blockSize)
        {
            throw new ArgumentException("Invalid padding length");
        }

        // Check if all padding bytes have the correct value
        for (var i = 0; i < paddingLength; i++)
        {
            if (input[input.Length - 1 - i] != paddingLength)
            {
                throw new ArgumentException("Invalid padding");
            }
        }

        // Create a new array with the size of input minus the padding length
        var output = new byte[input.Length - paddingLength];

        // Copy the data without the padding into the output array
        Array.Copy(input, output, output.Length);

        return output;
    }

    /// <summary>
    /// Gets the number of padding bytes in the given input data according to the PKCS7 padding scheme.
    /// </summary>
    /// <param name="input">The input data with PKCS7 padding. Must not be null and must have a valid padding.</param>
    /// <returns>The number of padding bytes in the input data.</returns>
    /// <exception cref="ArgumentException">

View on GitHub (pinned to 96e2905cab)