{"record":{"id":"67a747910e4d783f","repo":"TheAlgorithms/C-Sharp","slug":"invalid-padding-pkcs7padding","errorCode":null,"errorMessage":"Invalid padding","messagePattern":"Invalid padding","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Crypto/Paddings/Pkcs7Padding.cs","lineNumber":104,"sourceCode":"        {\n            throw new ArgumentException(\"Input length must be a multiple of block size\");\n        }\n\n        // Get the padding length from the last byte of input\n        var paddingLength = input[^1];\n\n        // Check if padding length is valid\n        if (paddingLength < 1 || paddingLength > blockSize)\n        {\n            throw new ArgumentException(\"Invalid padding length\");\n        }\n\n        // Check if all padding bytes have the correct value\n        for (var i = 0; i < paddingLength; i++)\n        {\n            if (input[input.Length - 1 - i] != paddingLength)\n            {\n                throw new ArgumentException(\"Invalid padding\");\n            }\n        }\n\n        // Create a new array with the size of input minus the padding length\n        var output = new byte[input.Length - paddingLength];\n\n        // Copy the data without the padding into the output array\n        Array.Copy(input, output, output.Length);\n\n        return output;\n    }\n\n    /// <summary>\n    /// Gets the number of padding bytes in the given input data according to the PKCS7 padding scheme.\n    /// </summary>\n    /// <param name=\"input\">The input data with PKCS7 padding. Must not be null and must have a valid padding.</param>\n    /// <returns>The number of padding bytes in the input data.</returns>\n    /// <exception cref=\"ArgumentException\">","sourceCodeStart":86,"sourceCodeEnd":122,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Crypto/Paddings/Pkcs7Padding.cs#L86-L122","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Verify keys, IVs, and modes match on both encrypt and decrypt sides.","Add authenticated encryption (HMAC or AES-GCM) to detect corrupted ciphertext.","Check the transport/storage path for truncation or modification.","Confirm padding was added by this same library before removal."],"exampleFix":"// before\nvar plain = padding.RemovePadding(corruptBytes);\n// after\nusing var aes = Aes.Create(); aes.Mode = CipherMode.GCM; // authenticated\nvar plain = padding.RemovePadding(gcm.Decrypt(...));","handlingStrategy":"try-catch","validationCode":"int len = input[^1];\nbool ok = len is >= 1 and <= blockSize && input[^len..].All(b => b == len);\nif (!ok) throw new CryptographicException(\"Corrupted padding detected\");","typeGuard":null,"tryCatchPattern":"try { plain = padding.RemovePadding(decrypted); }\ncatch (ArgumentException) { throw new CryptographicException(\"Decryption failed or data corrupted — check key/IV and integrity\"); }","preventionTips":["Use AEAD (AES-GCM) or encrypt-then-MAC to detect corruption before unpadding.","Verify keys/IVs match between parties.","Avoid padding-based decryption retries (padding oracle risk)."],"tags":["csharp","cryptography","data-corruption","padding"],"backgroundTag":"invalid-padding","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}