{"record":{"id":"dec1317364544250","repo":"TheAlgorithms/C-Sharp","slug":"input-cannot-be-null-pkcs7padding","errorCode":null,"errorMessage":"Input cannot be null","messagePattern":"Input cannot be null","errorType":"exception","errorClass":"ArgumentNullException","httpStatus":null,"severity":"error","filePath":"Algorithms/Crypto/Paddings/Pkcs7Padding.cs","lineNumber":132,"sourceCode":"        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\">\n    /// Thrown if the input data is null or has an invalid padding.\n    /// </exception>\n    /// <remarks>\n    /// This method uses bitwise operations to avoid branching.\n    /// </remarks>\n    public int GetPaddingCount(byte[] input)\n    {\n        if (input == null)\n        {\n            throw new ArgumentNullException(nameof(input), \"Input cannot be null\");\n        }\n\n        // Get the last byte of the input data as the padding value.\n        var lastByte = input[^1];\n        var paddingCount = lastByte & 0xFF;\n\n        // Calculate the index where the padding starts\n        var paddingStartIndex = input.Length - paddingCount;\n        var paddingCheckFailed = 0;\n\n        // Check if the padding start index is negative or greater than the input length.\n        // This is done by using bitwise operations to avoid branching.\n        // If the padding start index is negative, then its most significant bit will be 1.\n        // If the padding count is greater than the block size, then its most significant bit will be 1.\n        // By ORing these two cases, we can get a non-zero value rif either of them is true.\n        // By shifting this value right by 31 bits, we can get either 0 or -1 as the result.\n        paddingCheckFailed = (paddingStartIndex | (paddingCount - 1)) >> 31;\n","sourceCodeStart":114,"sourceCodeEnd":150,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Crypto/Paddings/Pkcs7Padding.cs#L114-L150","documentation":"GetPaddingCount rejects input that is null (or lacks valid PKCS7 padding) and reports it as a generic ArgumentException instead of ArgumentNullException, since the method requires a non-null padded buffer to count trailing padding bytes.","triggerScenarios":"Calling GetPaddingCount(null) — typically when a decryption step returned null (failed decrypt API, null from a cache or deserializer) and the result was passed straight through.","commonSituations":"A decrypt method that returns null on failure; nullable byte[] from external data pipelines; forgetting to handle an empty/failed read before unpadding.","solutions":["Check the array for null before calling GetPaddingCount.","Ensure the decrypt step always returns a buffer (or throw) instead of null.","If null means 'no data', skip unpadding entirely rather than calling.","Fail fast with a clear message at the data-source boundary."],"exampleFix":"// before\nvar count = padding.GetPaddingCount(decrypted); // decrypted may be null\n// after\nif (decrypted is null) throw new InvalidOperationException(\"Decryption produced no data\");\nvar count = padding.GetPaddingCount(decrypted);","handlingStrategy":"type-guard","validationCode":"if (decrypted is null) throw new InvalidOperationException(\"Decryption returned null\");","typeGuard":"static bool IsUnpaddable(byte[]? input) => input is not null && input.Length > 0;","tryCatchPattern":"try { count = padding.GetPaddingCount(input); }\ncatch (ArgumentNullException) { count = -1; /* treat as no data */ }","preventionTips":["Make decrypt methods non-null-returning (throw on failure instead).","Null-check results from external decrypt/cache/deserialize calls.","Use nullable reference types to catch null flow at compile time."],"tags":["csharp","null-reference","cryptography","padding"],"backgroundTag":"null-argument","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"}