Base64, decoded: padding, newlines and the btoa unicode trap
We encoded héllo in Python and in Node and got two different answers:
$ python3 -c 'import base64; print(base64.b64encode("héllo".encode("utf-8")).decode())'
aMOpbGxv
$ node -e 'console.log(btoa("héllo"))'
aOlsbG8=
Both are valid base64, of different bytes. UTF-8 gives héllo six bytes, btoa gives it five. That is one of three traps, and the only one that changes the output string. The other two change what the receiving side accepts: how much = padding a decoder demands, and whether a newline is legal.
TL;DR
DOMException: Invalid character:btoareads one Latin-1 byte per character, so an emoji throws andéencodes differently than in Python orBuffer. Encode to UTF-8 first.Incorrect padding: Python wants a length that is a multiple of 4, while Node'satob("YWI")returnsab. Restore the=, or look for a bad character.Only base64 data is allowed:encodebyteswraps at 76 characters, andvalidate=Truerejects the newline. Strip whitespace first.
Encode UTF-8 yourself and decode strictly, unless the input is wrapped
Encode to UTF-8 bytes yourself and decode with validate=True, unless your input is line-wrapped, in which case strip the whitespace first. Python needs three lines, Node two:
import base64
b64 = base64.b64encode(s.encode("utf-8")).decode("ascii")
text = base64.b64decode(b64, validate=True).decode("utf-8")
const b64 = Buffer.from(s, "utf8").toString("base64");
const text = Buffer.from(b64, "base64").toString("utf8");
The Python base64 docs say the default decoder discards characters outside the alphabet, and validate=True raises on them. A newline counts, so wrapped input fails (trap 3).
That strictness has a price. MIME email bodies and the Linux base64 command wrap at 76 characters, and PEM files wrap too. If your input comes from one of those, drop the flag or strip whitespace first with b64 = "".join(b64.split()).
Which error message do you have?
| Message | Usual cause | Fix |
|---|---|---|
DOMException: Invalid character (btoa) |
a character above Latin-1, such as an emoji | encode to UTF-8 bytes first (trap 1) |
Incorrect padding (Python) |
a stripped =, or an invalid character |
restore the padding, then scan for bad characters (trap 2) |
Only base64 data is allowed (Python) |
a newline in the input with validate=True
|
strip whitespace, or produce single-line b64encode output (trap 3) |
Trap 1: btoa reads Latin-1, so é changes the output and an emoji throws
btoa takes only characters that fit in one byte, so it encodes é as E9 where UTF-8 uses C3 A9. MDN's btoa page documents the one-byte limit. That one difference changes the output:
import base64
base64.b64encode("héllo".encode("utf-8")) # aMOpbGxv
base64.b64encode("héllo".encode("latin-1")) # aOlsbG8=
btoa("héllo"); // aOlsbG8=
Buffer.from("héllo", "utf8").toString("base64"); // aMOpbGxv
btoa("😀"); // DOMException: Invalid character
Buffer.from("😀", "utf8").toString("base64"); // 8J+YgA==
An emoji is four UTF-8 bytes and btoa has no single byte for it, so it throws. Python agrees with Buffer on the emoji:
base64.b64encode("😀".encode("utf-8")) # 8J+YgA==
Decoding has the mirror problem. atob("aMOpbGxv") returns héllo, six characters for five, because the two bytes C3 A9 arrive as two separate characters.
In a browser, with no Buffer, go through UTF-8 bytes yourself. Build the binary string in a loop, because String.fromCharCode(...bytes) can overflow the engine's argument limit on large inputs:
function toB64(s) {
let bin = "";
for (const b of new TextEncoder().encode(s)) bin += String.fromCharCode(b);
return btoa(bin);
}
function fromB64(b64) {
const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
Try this: search your code for
btoa(. Every call whose input can hold user text (names, emoji, pasted content) either throws or produces Latin-1-based base64 that a UTF-8 consumer will misread.
Trap 2: Node forgives a missing =, and Python's "Incorrect padding" can mean a bad character
Node accepts base64 with the = cut off, and Python demands a length that is a multiple of 4.
import base64
base64.b64decode("YWI") # raises: Incorrect padding
atob("YWI"); // "ab"
YWI is YWI= with its = removed. btoa writes the = when the last group is short (see aOlsbG8= above), so a value stripped by hand can pass your Node tests and still crash a Python consumer.
The same message can hide a second problem. Here is a four-character string, so its length is fine, with a * in it:
base64.b64decode("YW*j") # raises: Incorrect padding
Buffer.from("YW*j", "base64").toString(); // "ah", silently, skipping the bad character
Python blames the padding for a bad character, and Node decodes the string without complaint. The reason: default b64decode discards the *, leaving YWj, three characters, and that length triggers the padding error. So when you see Incorrect padding, check the length first, then scan for characters outside A-Z a-z 0-9 + /.
Never strip = by hand.
Trap 3: wrapped base64 passes in Node and fails Python's validate=True
You meet this when base64 arrives from something that wraps lines: a MIME email, a PEM file, the Linux base64 command, or Python's own encodebytes. A strict validator then rejects the value you copied.
data = bytes(range(100))
wrapped = base64.encodebytes(data)
len(wrapped.split(b"\n")[0]) # 76
base64.b64decode(wrapped) # works, newline discarded
base64.b64decode(wrapped, validate=True) # raises: Only base64 data is allowed
Node hides the problem. atob("YWJj\nZGVm") returns abcdef, so a test that passes in Node says nothing about a strict Python validator. If one sits downstream, such as an API that checks the alphabet, send b64encode output, which is a single line. When you receive wrapped input, strip the whitespace before you validate.
JWT segments need their padding back before Python decodes them
Pass an unpadded JWT segment such as eyJzdWIiOiIxIn0 to plain base64.b64decode and Python raises Incorrect padding, while Node's atob returns {"sub":"1"}. JWT segments drop the = and use the URL-safe alphabet, which swaps + for - and / for _. Nine bytes show the swap, two characters differing:
payload = bytes.fromhex("D2 DF EC F9 06 13 20 2D 3A")
base64.b64encode(payload) # 0t/s+QYTIC06
base64.urlsafe_b64encode(payload) # 0t_s-QYTIC06
Plain b64decode silently discards - and _. A constructed example: eyJzdWIiOiIxIn0-x decodes to b'{"sub":"1"}1', a corrupted extra byte, while a dash mid-string (eyJ-zdWIiOiIxIn0) raises Incorrect padding. Restore the padding, then decode with the URL-safe function:
seg = segment + "=" * (-len(segment) % 4)
base64.urlsafe_b64decode(seg) # b'{"sub":"1"}'
Check one value from your pipeline
This check only applies if the payload is single-line, standard-alphabet text. It tests the alphabet, the padding and whether the bytes are valid UTF-8:
import base64
def check(v):
return base64.b64decode(v, validate=True).decode("utf-8")
check("aMOpbGxv") # 'héllo'
check("aOlsbG8=") # raises UnicodeDecodeError (Latin-1 bytes)
check("YWI") # raises: Incorrect padding
Takeaways
- Encode text to UTF-8 bytes before you base64 it.
- On
Incorrect padding, check the length, then the characters.- Strip whitespace before a strict decode.
Top comments (0)