โ† Back to Blog

Base64 Decode Troubleshooting Guide

2026-04-20 ยท 5 min read

โ† Back to Blog

Base64 Decode Troubleshooting Guide

ยท 5 min read

Error 1: Invalid Padding

This is the most common Base64 decoding error. Python's error message is binascii.Error: Incorrect padding, Java's is IllegalArgumentException: Invalid base64 character. The root cause is that the Base64 string length is not a multiple of 4. Common triggers: trailing equals signs lost when copying Base64 strings (truncated by UI); Base64URL strings (unpadded) passed to a decoder expecting standard Base64; equals signs getting percent-decoded to something else during URL transmission.

# ่งฃๅ†ณๆ–นๆกˆ๏ผš่‡ชๅŠจ่กฅๅ…จๅกซๅ…… / Solution: Auto-add padding
import base64

def fix_padding(s):
    """่กฅๅ…จ Base64 ๅญ—็ฌฆไธฒ็š„ๅกซๅ……ๅญ—็ฌฆ"""
    if isinstance(s, bytes):
        s = s.decode('ascii')
    # ๅŽปๆމๅทฒๆœ‰็š„็ญ‰ๅทๅ†้‡ๆ–ฐ่กฅๅ…จ๏ผˆ้˜ฒๆญข้‡ๅคๅกซๅ……๏ผ‰
    s = s.rstrip('=')
    padding = 4 - len(s) % 4
    if padding != 4:
        s += '=' * padding
    return s

def safe_decode(s):
    fixed = fix_padding(s)
    return base64.b64decode(fixed)

# ๆต‹่ฏ• / Test
print(safe_decode("SGVsbG8"))     # b'Hello'
print(safe_decode("SGVsbG8="))    # b'Hello'
print(safe_decode("SGVsbG8=="))   # b'Hello'

Error 2: Invalid Characters

When a Base64 string contains non-Base64 characters, decoding will fail. Common sources of illegal characters: HTML entities (& accidentally inserted); JSON string escape sequences (\n, \r) literally included; copying included prefix descriptive text (like "Base64: SGVsbG8="); URL-encoded plus signs (%2B) not URL-decoded first; newlines (MIME Base64 has newlines every 76 characters) not cleaned up.

import base64
import re

def clean_and_decode(s):
    """ๆธ…็†ๅนถ่งฃ็  Base64 ๅญ—็ฌฆไธฒ"""
    if isinstance(s, bytes):
        s = s.decode('ascii', errors='ignore')

    # ๅŽป้™คๆ‰€ๆœ‰็ฉบ็™ฝๅญ—็ฌฆ๏ผˆ็ฉบๆ ผใ€ๆข่กŒใ€Tab๏ผ‰
    s = re.sub(r'\s+', '', s)

    # ๅฆ‚ๆžœๆ˜ฏ URL-encoded๏ผŒๅ…ˆ decode
    if '%' in s:
        from urllib.parse import unquote
        s = unquote(s)

    # ๆฃ€ๆต‹ๆ˜ฏๅฆๆ˜ฏ Base64URL๏ผˆๅซ - ๆˆ– _๏ผ‰
    if '-' in s or '_' in s:
        s = s.replace('-', '+').replace('_', '/')

    # ่กฅๅ…จๅกซๅ……
    s = s.rstrip('=')
    padding = 4 - len(s) % 4
    if padding != 4:
        s += '=' * padding

    return base64.b64decode(s)

# ๅค„็† MIME ๆ ผๅผ็š„ Base64๏ผˆๅซๆข่กŒ๏ผ‰
mime_b64 = """
SGVsbG8gV29ybGQh
SGVsbG8gV29ybGQh
"""
result = clean_and_decode(mime_b64)
print(result)

Error 3: Charset Issues Causing Garbled Text

Successfully decoded Base64 data but got garbled text. This usually happens with charset mismatches: original data was GBK-encoded (common in old Chinese systems) but decoded with UTF-8; or the reverse, UTF-8 data decoded with Latin-1.

import base64

# ๅฝ“่งฃ็ ็ป“ๆžœๆ˜ฏไนฑ็ ๆ—ถ๏ผŒๅฐ่ฏ•ไธๅŒๅญ—็ฌฆ้›†
# When decoded result is garbled, try different charsets
def try_decode_charsets(base64_str):
    try:
        raw = base64.b64decode(base64_str)
    except Exception as e:
        return f"Base64 decode error: {e}"

    charsets = ['utf-8', 'gbk', 'gb2312', 'latin-1',
                'utf-16', 'shift-jis', 'euc-jp']
    results = {}
    for cs in charsets:
        try:
            decoded = raw.decode(cs)
            results[cs] = decoded[:50]  # ๅชๆ˜พ็คบๅ‰50ๅญ—็ฌฆ
        except (UnicodeDecodeError, LookupError):
            results[cs] = '(decode failed)'
    return results

# ็คบไพ‹ / Example
sample = base64.b64encode("ไฝ ๅฅฝไธ–็•Œ".encode('gbk')).decode()
print(try_decode_charsets(sample))

Error 4: Confusing Standard Base64 with Base64URL

Standard Base64 uses + and /, while Base64URL uses - and _. If a Base64URL string is passed to a standard Base64 decoder, - and _ will be treated as illegal characters, causing decode failure or incorrect results. This is especially relevant when handling JWT, OAuth tokens, and PKCE code_challenge โ€” all of which use Base64URL.

// JavaScript๏ผšๆฃ€ๆต‹ๅนถๅค„็†ไธค็งๅ˜ไฝ“
// JavaScript: Detect and handle both variants
function universalBase64Decode(s) {
  // ๆฃ€ๆต‹ๆ˜ฏๅฆๆ˜ฏ Base64URL๏ผˆๅซ - ๆˆ– _๏ผŒไธๅซ + ๆˆ– /๏ผ‰
  const isBase64URL = /[-_]/.test(s) && !/[+/]/.test(s);

  if (isBase64URL) {
    // Base64URL โ†’ ๆ ‡ๅ‡† Base64
    s = s.replace(/-/g, '+').replace(/_/g, '/');
  }

  // ่กฅๅ…จๅกซๅ……
  const rem = s.length % 4;
  if (rem === 2) s += '==';
  else if (rem === 3) s += '=';

  try {
    return atob(s);
  } catch (e) {
    throw new Error(`Failed to decode: ${e.message}`);
  }
}

Error 5: Truncated Data

Truncated Base64 strings are a tricky problem because the truncated string may still be valid Base64 format (if the truncation point falls exactly on a 4-byte boundary), but the decoded data is incomplete. Common causes: field length limits truncating Base64 strings (like database VARCHAR length, HTTP header size limits); log systems truncating long lines; frontend JavaScript truncating Base64 strings for display.

Methods to detect truncation: for files with known formats (images, PDFs), check the file header's magic bytes after decoding. PNG starts with \x89PNG, JPEG starts with \xFF\xD8\xFF, PDF starts with %PDF-. If the file header is correct but the file won't open, the tail may be truncated.

General Troubleshooting Steps

  1. Check if string length is a multiple of 4 (with padding)
  2. Check for non-Base64 characters (spaces, newlines, special characters)
  3. Confirm which Base64 variant is used (standard vs Base64URL)
  4. Try decoding with an online tool and check for clear error messages
  5. If decoding succeeds but produces garbled text, try different charsets
  6. Verify the original data is complete (check file magic bytes or data length)

Using our online Base64 tool, you can conveniently test various inputs and get immediate decoding results, making it a powerful aid for troubleshooting Base64 issues.

Try the online tool now โ€” no installation, completely free.

Open Tool โ†’

Try the free tool now

Use Free Tool โ†’