How to Fix "base64: invalid input" and Padding Errors
When terminal decoders or API parsers fail with "base64: invalid input", the bug almost always traces back to five predictable wrappers or a single truncated character. Learn how to diagnose each one in seconds.
Five Predictable Wrappers Behind "base64: invalid input"
Spot Data URI prefixes, JSON-escaped forward slashes, Base64URL alphabets, whitespace breaks, and missing padding in seconds.
Read full technical details
Standard RFC 4648 Base64 permits strictly 65 characters: A–Z, a–z, 0–9, +, /, and trailing =. The instant any strict decoder hits a symbol outside that table—such as a wrapping quotation mark from JSON or the comma inside data:image/png;base64,—it aborts with "base64: invalid input".
JSON serialization hides a notorious visual trap: serializers in PHP, Java, and legacy gateways escape every forward slash as \/. Across a 10,000-character PDF payload, \/ blends seamlessly into surrounding letters, yet the backslash halts strict decoders at that exact character.
Meanwhile, JWT headers, OAuth tokens, and modern URL cursors rely on RFC 4648 §5 Base64URL, replacing + and / with - and _ while dropping trailing = padding—tripping standard GNU base64 -d and JavaScript atob() calls immediately.
Safe Wrapper Normalization vs Dangerous Blind Character Stripping
Pinpoint exact 1-based error coordinates and check modulo-4 lengths instead of blindly stripping random letters that shift downstream bytes.
Read full technical details
Running naive regex filters like replace(/[^A-Za-z0-9+/=]/g, "") across corrupt payloads is dangerous for binary documents: if someone accidentally pasted a status label or lost two characters mid-stream, deleting stray letters shifts every subsequent 6-bit boundary and turns the rest of the PDF into garbage.
Safe repair removes only deterministic transport wrappers (leading data:*;base64, headers, matching outer quotes, JSON \/ escapes, whitespace, and missing trailing =) and validates everything else strictly—reporting line, column, and Unicode code point (catching invisible U+200B zero-width spaces from chat clients).
Finally, remember the modulo-4 invariant: valid unpadded Base64 length % 4 can only equal 0, 2, or 3. Any cleaned string with length % 4 === 1 has 1 leftover 6-bit character—mathematically proving truncation that padding cannot fix.
Checking Concatenated Chunk Padding & Invisible Unicode Artifacts
Spot non-terminal = characters from misaligned multi-chunk joins and invisible U+200B zero-width spaces copied out of messaging apps.
Read full technical details
Two subtle errors trip engineers even after removing Data URIs and JSON slashes. First, concatenating independently encoded 64 KB blocks injects = or == mid-stream because 65,536 is not divisible by 3; RFC 4648 forbids = anywhere except the final two characters. Second, Slack, Teams, or Confluence rich-text blocks frequently inject zero-width spaces (U+200B) or curly quotes around copied strings—triggering instant failures on strict terminal decoders.
Production Reference Code
# Strip Data URI prefix, JSON \/ escapes, whitespace, and normalize URL-Safe chars before decoding
printf '%s' "$RAW" | sed -e 's/^data:[^;]*;base64,//' -e 's/\\\//\//g' | tr -d ' \r\n' | tr '_-' '/+' | base64 -d > out.binStep-by-Step Local Workflow
Check Cleaned Length Modulo 4
Verify character count: mod 2 takes ==, mod 3 takes =, and mod 1 proves truncation or an extra stray character.
Strip Outer Data URI & Quotes
Remove leading data:<mime>;base64, prefixes and wrapping single or double quotation marks copied from logs.
Unescape JSON Forward Slashes
Replace JSON-escaped \/ back into / and collapse literal \r\n sequences or spaces.
Normalize URL-Safe - and _
Map - to + and _ to / whenever passing RFC 4648 §5 Base64URL payloads into standard decoders.
Test Directly in Browser Workbench
Frequently Asked Questions
Why does length % 4 === 1 mean my Base64 string is permanently corrupted?
Yes, 3 bytes encode to 4 Base64 chars, 1 byte to 2 chars, and 2 bytes to 3 chars; 1 leftover character carries only 6 bits and cannot reconstruct a whole 8-bit byte.
Can GNU coreutils base64 -d fail simply because of trailing spaces or bad line breaks?
GNU base64 -d ignores newlines when decoding, whereas macOS base64 -D and strict API validators reject unexpected spaces, Data URI commas, or unpadded URL-Safe tokens.
How do I locate the exact bad character inside a 50,000-character Base64 block?
Paste the string into Base64Doc Validator to read the exact 1-based line number, column number, and Unicode code point (such as U+200B) immediately.
Does stripping whitespace alter binary PDF or Excel content?
No, whitespace is excluded from the RFC 4648 alphabet; RFC 2045 MIME-76 inserts CRLF every 76 chars strictly for legacy email line wrapping.
What if my Data URI header has the wrong MIME type like image/png on a JPEG?
Base64Doc inspects decoded magic bytes (FF D8 FF for JPEG vs 89 50 4E 47 for PNG) after stripping the prefix and generates a repaired Data URI header automatically.