{"record":{"id":"a033f2da0214268b","repo":"TheAlgorithms/Java","slug":"padding-can-only-appear-at-the-end-last-1-or","errorCode":null,"errorMessage":"Padding '=' can only appear at the end (last 1 or 2 characters)","messagePattern":"Padding '=' can only appear at the end \\(last 1 or 2 characters\\)","errorType":"exception","errorClass":"IllegalArgumentException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/conversions/Base64.java","lineNumber":124,"sourceCode":"    public static byte[] decode(String input) {\n        if (input == null) {\n            throw new IllegalArgumentException(\"Input cannot be null\");\n        }\n\n        if (input.isEmpty()) {\n            return new byte[0];\n        }\n\n        // Strict RFC 4648 compliance: length must be a multiple of 4\n        if (input.length() % 4 != 0) {\n            throw new IllegalArgumentException(\"Invalid Base64 input length; must be multiple of 4\");\n        }\n\n        // Validate padding: '=' can only appear at the end (last 1 or 2 chars)\n        int firstPadding = input.indexOf('=');\n        if (firstPadding != -1) {\n            if (firstPadding < input.length() - 2) {\n                throw new IllegalArgumentException(\"Padding '=' can only appear at the end (last 1 or 2 characters)\");\n            }\n            for (int i = firstPadding; i < input.length(); i++) {\n                if (input.charAt(i) != '=') {\n                    throw new IllegalArgumentException(\"A padding '=' must not be followed by a non-padding character\");\n                }\n            }\n        }\n\n        List<Byte> result = new ArrayList<>();\n\n        // Process input in groups of 4 characters\n        for (int i = 0; i < input.length(); i += 4) {\n            // Get up to 4 characters\n            int char1 = getBase64Value(input.charAt(i));\n            int char2 = getBase64Value(input.charAt(i + 1));\n            int char3 = input.charAt(i + 2) == '=' ? 0 : getBase64Value(input.charAt(i + 2));\n            int char4 = input.charAt(i + 3) == '=' ? 0 : getBase64Value(input.charAt(i + 3));\n","sourceCodeStart":106,"sourceCodeEnd":142,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/conversions/Base64.java#L106-L142","documentation":"Base64.decode enforces that the '=' padding character may only appear in the last one or two positions of the input. Padding earlier in the string (firstPadding < length - 2) indicates corruption, mis-encoding, or a string that was concatenated incorrectly. RFC 4648 permits at most two trailing '=' characters.","triggerScenarios":"Input like \"AB=C\" where '=' appears in the middle. Input with three or more trailing '=' characters. Input where padding was inserted at the wrong position during manual construction.","commonSituations":"Manually building Base64 strings without proper padding logic. Corrupted data from a transport that inserted characters. Copy errors when transcribing tokens.","solutions":["Re-encode the original bytes with a standard Base64 encoder rather than constructing strings by hand.","Validate padding position before calling decode and reject/repair the source data.","Use java.util.Base64.getDecoder() which enforces the same rules but gives clearer standard error messages."],"exampleFix":"// before\nString bad = \"AB=CD===\";\nbyte[] out = Base64.decode(bad); // '=' too early\n\n// after\nString good = Base64.encodeString(originalBytes); // let encoder place padding\nbyte[] out = Base64.decode(good);","handlingStrategy":"validation","validationCode":"String s = input.replaceAll(\"\\\\s\", \"\");\nint firstPad = s.indexOf('=');\nif (firstPad != -1 && firstPad < s.length() - 2) {\n    throw new IllegalArgumentException(\"padding misplaced\");\n}\nbyte[] out = Base64.decode(s);","typeGuard":"static boolean hasValidPaddingPosition(String s) {\n    s = s.replaceAll(\"\\\\s\", \"\");\n    int fp = s.indexOf('=');\n    return fp == -1 || fp >= s.length() - 2;\n}","tryCatchPattern":"try {\n    byte[] out = Base64.decode(input);\n} catch (IllegalArgumentException e) {\n    throw new DomainException(\"Malformed Base64: \" + e.getMessage(), e);\n}","preventionTips":["Never construct Base64 strings by hand; use an encoder.","Strip whitespace before decoding.","Validate against ^[A-Za-z0-9+/]*={0,2}$ before calling decode."],"tags":["conversions","base64","rfc-4648","padding","validation","java"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}