Originally published on DevToolsHub — free, privacy-first online tools for developers.
You paste a Base64 string into your decoder, hit enter, and get
InvalidCharacterError in JavaScript or
binascii.Error in Python. Annoyingly, the string
looks perfectly fine — just letters, numbers, maybe an equals
sign. The problem is almost never exotic: in practice, broken Base64
comes down to five specific causes, and each one has a one-line fix.
This guide covers all five — missing padding, URL-safe characters,
embedded whitespace, data URL prefixes, and character encoding
mismatches — with copy-paste repair code for JavaScript and Python, plus
a decoder error cheat sheet at the end.
💡 Quick Try Not sure which problem your string has? Paste it into our free
Base64 Encoder / Decoder
— it runs entirely in your browser, handles padding and URL-safe
variants automatically, and tells you exactly what was wrong.
Base64 in 30 Seconds
Base64 encodes every **3 bytes of binary data into 4
characters**, using an alphabet of `A–Z`,
`a–z`, `0–9`, `+`, and `/`.
Because input rarely divides evenly into 3-byte groups, the last chunk
is padded with one or two `=` characters so the total length
is always a multiple of 4. That rule —
**length must be a multiple of 4** — is the first thing to
check on any failing string, and the strict alphabet is the second:
anything outside those 65 characters (spaces, newlines,
`-`, `_`) is invalid to a strict decoder.
Cause 1: Missing Padding
The most common offender. Systems that strip `=` for compact
storage (some JWT libraries, URL shorteners, certain S3 tools) hand you
a string of length 42 or 171 — not a multiple of 4 — and strict
decoders refuse it. The fix is to pad the length up to the next
multiple of 4:
// JavaScript: restore missing padding
function padBase64(str) {
return str.padEnd(str.length + (4 - (str.length % 4)) % 4, '=');
}
atob(padBase64('aGVsbG8')); // works even without the trailing '='
# Python: add_padding via the modulo dance
def pad_b64(s: str) -> str:
return s + "=" * (-len(s) % 4)
import base64
base64.b64decode(pad_b64("aGVsbG8")) # b'hello'
The expression `-len(s) % 4` is a neat Python idiom: it
yields exactly the number of `=` characters needed (0, 1, or
2). Note that padding is technically optional information — many
decoders accept unpadded input — but strict ones like
`atob()` and Python's `validate=True` mode
will not, so normalizing before decode is the safe habit.
Cause 2: URL-Safe Characters (- and _)
Standard Base64 uses `+` and `/` — both awkward
inside URLs and filenames (`/` is a path separator,
`+` decodes to a space in query strings). The URL-safe
variant replaces them with `-` and `_`. You will
see it in **JWTs** (every segment of
`eyJhbGci..._...`), OAuth tokens, and file names. Feed a
URL-safe string to a strict standard decoder and it throws on the very
first `-`. Convert the alphabet back before decoding:
// JavaScript: URL-safe -> standard, then pad
function fromUrlSafe(str) {
const standard = str.replace(/-/g, '+').replace(/_/g, '/');
return padBase64(standard); // from Cause 1
}
// Decode the middle segment of a JWT
const payload = JSON.parse(atob(fromUrlSafe(jwt.split('.')[1])));
# Python: urlsafe_b64decode does the mapping for you
import base64, json
payload = json.loads(base64.urlsafe_b64decode(
jwt.split('.')[1] + "=" * (-len(jwt.split('.')[1]) % 4)
))
This is exactly what our
[
JWT Decoder
](https://devtoolshub.cloud/tools/jwt-decoder)
handles behind the scenes — paste a token and both URL-safe decoding
and padding repair happen automatically.
Cause 3: Whitespace in the Middle
Email MIME lines wrap at 76 characters, PEM certificates wrap at 64,
and copied text from terminals or PDFs picks up stray newlines and
spaces. Every one of those characters is outside the Base64 alphabet,
so a strict decoder dies mid-string even though a human sees nothing
wrong. The fix is to strip all whitespace before decoding:
// JavaScript: remove all whitespace anywhere in the string
const clean = raw.replace(/\\s+/g, '');
const decoded = atob(clean); // now safe
// \\s matches spaces, tabs, newlines (\\n, \\r) and more
# Python: join all lines, then strip the rest
import re
clean = re.sub(r"\\s+", "", raw)
base64.b64decode(clean, validate=True) # strict mode passes now
Beware of a related trap: **trailing NUL bytes**. Some
tools append `\\x00` when slicing buffers; whitespace
stripping will not remove those, and you will still get a validation
error. If cleaning whitespace does not fix it, inspect the string's
raw bytes (length parity against the expected 4-multiple is a quick
tell).
Cause 4: A data: URL Prefix
Copying an embedded image from HTML or CSS hands you something that
starts with `data:image/png;base64,` — the
[
URL encoding rules
](https://devtoolshub.cloud/tools/url-encoder)
for data URLs mean the prefix itself is metadata, not payload. Feeding
the whole thing to a decoder fails immediately on the colon. Strip
everything up to and including the comma first:
// JavaScript: peel off the data URL header
function stripDataUrl(input) {
const idx = input.indexOf(',');
return idx !== -1 ? input.slice(idx + 1) : input;
}
atob(stripDataUrl('data:image/png;base64,iVBORw0KGgo...')) // clean payload
# Python: split on the comma, keep the payload
payload = data_url.split(",", 1)[1] if "," in data_url else data_url
base64.b64decode(payload)
Bonus: the part before the comma tells you the MIME type (
`image/png`, `application/pdf`) — save it if you
plan to write the decoded bytes to a file with the right extension.
Cause 5: Character Encoding Mismatch
Sometimes the string *decodes fine* but the output is mojibake —
`ä½ å¥½` instead of `你好`. This is not a Base64
problem at all: Base64 transports raw bytes, and
**those bytes must be decoded with the same character encoding
they were encoded from**. The classic failure is one side using
UTF-8 and the other treating bytes as Latin-1:
// JavaScript: atob returns a 'binary string' (one char per byte)
// Decode it as UTF-8 explicitly, or multibyte text garbles:
const bin = atob('5L2g5aW9'); // bytes for UTF-8 你好
const bytes = Uint8Array.from(bin, c => c.charCodeAt(0));
const text = new TextDecoder('utf-8').decode(bytes);
console.log(text); // '你好' — correct
// Wrong: treating the binary string as Latin-1
console.log(bin); // 'ä½ å¥½' — mojibake
// Encoding TO Base64 with non-Latin1 text needs the same care:
btoa(String.fromCharCode(...new TextEncoder().encode('你好')));
# Python: decode bytes with the matching encoding
import base64
raw = base64.b64decode('5L2g5aW9')
print(raw.decode('utf-8')) # 你好 — matches how it was encoded
print(raw.decode('latin-1')) # ä½ å¥½ — wrong encoding, garbage
Rule of thumb: **UTF-8 everywhere**. If a partner system
insists on Latin-1, encode from that encoding explicitly on both ends —
never let the default assumption decide.
Decoder Error Cheat Sheet
| Error | Language | Likely Cause → Fix |
|---|---|---|
| InvalidCharacterError | JavaScript (atob / btoa) | Bad chars, missing padding, or prefix → Causes 1–4 |
| binascii.Error: Invalid base64-encoded string | Python (b64decode) | Wrong length or bad chars → pad and strip |
| binascii.Error: Invalid character | Python (validate=True) | Whitespace, URL-safe chars, or NUL → Causes 2–3 |
| Incorrect padding | Python | Length not multiple of 4 → Cause 1 |
| Mojibake (decodes, but garbage text) | Any | Encoding mismatch → Cause 5 |
Debugging Strategy That Always Works
When you cannot tell which of the five it is, normalize everything at
once — strip whitespace, strip the data URL prefix, translate the
URL-safe alphabet, and restore padding. A string that survives all four
steps and still fails is genuinely corrupt, not merely
mangled in transit:
// JavaScript: universal repair before atob()
function sanitizeBase64(input) {
let s = input.trim();
const comma = s.indexOf(','); // drop data: URL prefix
if (s.startsWith('data:') && comma !== -1) s = s.slice(comma + 1);
s = s.replace(/\\s+/g, ''); // remove all whitespace
s = s.replace(/-/g, '+').replace(/_/g, '/'); // URL-safe -> standard
return s.padEnd(s.length + (4 - (s.length % 4)) % 4, '=');
}
atob(sanitizeBase64(broken));
Common Mistakes & How to Avoid Them
-
**Assuming the string is corrupt when it is just non-standard.**
URL-safe or unpadded Base64 is valid data in a different dialect —
translate and pad before declaring it broken.
-
**Stripping whitespace only at the ends.**
`.trim()` misses the MIME line breaks buried mid-string
that actually break decoding. Remove whitespace
*everywhere* with `/\\s+/g`.
-
**Double-encoding by accident.** If your decoded output
still looks like Base64 (`U29tZXRoaW5n...`), the payload
was encoded twice — decode again rather than debugging garbage.
-
**Using btoa() on Unicode text directly.**
`btoa('你好')` throws InvalidCharacterError
because btoa only accepts Latin-1. Always route through
`TextEncoder` first.
-
**Confusing a JSON payload with the encoding problem.**
If the decoded bytes are valid Base64 output but unparseable as JSON,
check for a UTF-8 BOM or a stray prefix — the Base64 layer did its
job correctly.
Frequently Asked Questions
How do I fix InvalidCharacterError in JavaScript?
The error means atob() or btoa() received a character outside the
Base64 alphabet. In order: strip a data URL prefix if present,
remove all whitespace, translate URL-safe - and
_ to + and /, and pad the
length to a multiple of 4. If you are encoding rather than
decoding, the usual culprit is non-Latin1 text passed straight
into btoa() — encode with TextEncoder first.
Does Base64 padding matter?
Technically the = characters are redundant — the byte
count is derivable from the data characters alone, which is why
JWTs and many APIs omit them. But strict decoders (atob,
b64decode with validate=True) require the total length to be a
multiple of 4 and reject unpadded input. The safe habit: normalize
padding yourself before decoding, and only omit padding when the
protocol you are targeting explicitly allows it.
Why does decoded Base64 show weird characters?
The decode succeeded — the output is being interpreted with the
wrong character encoding. Base64 transports raw bytes; seeing
ä½ å¥½ instead of 你好 means UTF-8 bytes
are being read as Latin-1 (or vice versa). Decode the resulting
bytes explicitly as UTF-8 — in JavaScript with
new TextDecoder("utf-8") on a Uint8Array,
in Python with raw.decode("utf-8").
Is URL-safe Base64 still valid Base64?
Yes — it is a standardized variant (RFC 4648 section 5) that swaps
+ for - and / for
_ so the string survives URLs, path segments, and
filenames unchanged. It encodes the exact same bytes; only the
alphabet differs. Strict standard-alphabet decoders will reject it
though, so translate the two characters back (and pad) before
using such a decoder.
Can I decode Base64 locally without uploading?
Yes. Our
Base64 Encoder / Decoder
runs entirely in your browser with JavaScript — the string never
leaves your machine, so it is safe for tokens, API keys, and
proprietary payloads. The same is true of our
JWT Decoder
and
URL Encoder / Decoder
: all client-side, all instant, nothing logged.
**Related Tools:**
[Base64 Encoder / Decoder](https://devtoolshub.cloud/tools/base64)
[URL Encoder / Decoder](https://devtoolshub.cloud/tools/url-encoder)
[JWT Decoder](https://devtoolshub.cloud/tools/jwt-decoder)
Top comments (0)