{"record":{"id":"01a98dce5b21ebd5","repo":"TheAlgorithms/C-Sharp","slug":"invalid-padding-length-pkcs7padding","errorCode":null,"errorMessage":"Invalid padding length","messagePattern":"Invalid padding length","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Crypto/Paddings/Pkcs7Padding.cs","lineNumber":96,"sourceCode":"    /// <returns>The input data without the padding as a new byte array.</returns>\n    /// <exception cref=\"ArgumentException\">\n    /// Thrown if the input data is null, has an invalid length, or has an invalid padding.\n    /// </exception>\n    public byte[] RemovePadding(byte[] input)\n    {\n        // Check if input length is a multiple of blockSize\n        if (input.Length % blockSize != 0)\n        {\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;","sourceCodeStart":78,"sourceCodeEnd":114,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Crypto/Paddings/Pkcs7Padding.cs#L78-L114","documentation":"PKCS#7 padding length is encoded in the final byte and must be at least 1 and at most blockSize. If the last byte falls outside that range, the data cannot be validly PKCS#7-padded, so RemovePadding throws ArgumentException. This usually means wrong data, wrong key, or a different padding scheme.","triggerScenarios":"Calling RemovePadding on input whose last byte is 0x00 or greater than blockSize — e.g. unpadded data, data padded with another scheme (ISO/IEC 7816-4, ANSI X9.23, zero padding), or output decrypted with a wrong key/IV producing garbage.","commonSituations":"Decrypting with the wrong key so the last byte is random; switching padding schemes between encrypt and decrypt; stripping padding twice; receiving unpadding raw data from an external source.","solutions":["Verify the encryption and decryption use the same key and IV.","Confirm the data was encrypted with PKCS7 padding, not another scheme.","Decrypt before unpadding; never call RemovePadding on ciphertext.","Validate the data integrity (e.g. HMAC) to catch corrupted ciphertext early."],"exampleFix":"// before\nvar plain = padding.RemovePadding(raw); // raw was never PKCS7-padded\n// after\nvar decrypted = cipher.Decrypt(raw);\nvar plain = padding.RemovePadding(decrypted);","handlingStrategy":"try-catch","validationCode":"var last = input[^1];\nif (last < 1 || last > blockSize)\n    throw new CryptographicException(\"Last byte is not a valid PKCS7 padding length — wrong key or wrong padding scheme?\");","typeGuard":null,"tryCatchPattern":"try { plain = padding.RemovePadding(decrypted); }\ncatch (ArgumentException) { throw new CryptographicException(\"Invalid padding: verify key/IV and padding scheme\"); }","preventionTips":["Authenticate ciphertext (HMAC/GCM) so garbage never reaches unpadding.","Never call RemovePadding on ciphertext or unpadded data.","Use the same padding library/scheme on both sides."],"tags":["csharp","cryptography","padding","wrong-key"],"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"}