The = at the end of a base64 string is padding. Base64 turns every 3 bytes of input into 4 characters, and when the input length isn't a multiple of 3 the last group comes up short. One leftover byte becomes two characters plus ==. Two leftover bytes become three characters plus =. That's why you only ever see zero, one or two equals signs, never three. The padding carries no data, so a decoder can work out where it belongs from the length alone, which is why many formats leave it off and why "Incorrect padding" is such a common decode error.
How 3 bytes become 4 characters
Base64 regroups bits. Three bytes are 24 bits, and 24 bits split evenly into four 6-bit values. Each 6-bit value (0 to 63) picks one character from a 64-character alphabet: A-Z, a-z, 0-9, + and /. RFC 4648, section 4 defines this and lists the three ways the input can end:
- The input is a multiple of 24 bits: the output is a multiple of 4 characters with no padding.
- The last group is exactly 8 bits: "two characters followed by two "=" padding characters".
- The last group is exactly 16 bits: "three characters followed by one "=" padding character".
Running the RFC's own test strings through Python's base64.b64encode shows the pattern repeating every three bytes:
import base64
for s in [b"f", b"fo", b"foo", b"foob", b"fooba", b"foobar"]:
print(f"{s.decode():<7} {len(s)} bytes -> {base64.b64encode(s).decode()}")
f 1 bytes -> Zg==
fo 2 bytes -> Zm8=
foo 3 bytes -> Zm9v
foob 4 bytes -> Zm9vYg==
fooba 5 bytes -> Zm9vYmE=
foobar 6 bytes -> Zm9vYmFy
Take "f" on its own. It is one byte, 01100110. The first six bits, 011001, are 25, which is Z. That leaves two bits, 10, which aren't enough for a character, so the encoder adds four zero bits to get 100000, which is 32, or g. Two characters hold the 8 real bits. The group still needs four characters, so == fills the last two slots.
The rule for the number of = signs is (3 - len(data) % 3) % 3. The encoded length, padding included, is always 4 * ceil(len(data) / 3).
Why there are never three equals signs
Three = would mean the last group held one character, which is only 6 bits. That isn't enough for even one byte, so no input can produce it. The same arithmetic tells a decoder that an unpadded string whose length is 4n + 1 is broken, not just missing its padding. Python says so directly when you try:
binascii.Error: Invalid base64-encoded string: number of data characters (5) cannot be 1 more than a multiple of 4
An unpadded length of 4n + 2 needs ==, 4n + 3 needs =, and 4n needs nothing. That's how decoders that accept unpadded input put the padding back. Appendix C of RFC 7515 (JSON Web Signature) shows a decoder that does exactly this and rejects the 4n + 1 case as an illegal string.
Is padding required?
The spec says yes by default. RFC 4648 section 3.2 says implementations "MUST include appropriate pad characters at the end of encoded data unless the specification referring to this document explicitly states otherwise". The reason it gives is that without padding you need to know the size of the data some other way.
Plenty of specifications do say otherwise. URL-safe base64 (base64url, section 5 of the RFC) swaps + and / for - and _, and the RFC notes that = would have to be percent-encoded in a URL, "but if the data length is known implicitly, this can be avoided by skipping the padding". JWTs rely on that. RFC 7515 defines its base64url "with all trailing '=' characters omitted", which is why the three dot-separated parts of a token never end in =.
So in practice there are two families: padded standard base64 (email, data URLs, most APIs that return binary as text) and unpadded base64url (JWT, many URL tokens). Most padding errors come from feeding one family to a decoder that expects the other.
Fixing "Incorrect padding" and friends
Here is what each common decoder does with Zm9vYg, which is "foob" with its == removed.
Python
By default b64decode wants the padding:
>>> base64.b64decode("Zm9vYg")
binascii.Error: Incorrect padding
The portable fix, which works on any Python version, is to add back as many = as the length needs:
def add_padding(s: str) -> str:
return s + "=" * (-len(s) % 4)
base64.b64decode(add_padding("Zm9vYg")) # b'foob'
-len(s) % 4 gives 2 for a 6-character string and 1 for a 7-character one. For a 5-character string it gives 3, which makes a string the decoder rejects anyway, and that's the right outcome. Don't just append "==" to everything. The default decoder will often accept the extra =, which hides the difference between a truncated string and a valid one.
Python 3.15 makes this simpler. The base64 module docs list a new padded keyword on b64decode, and urlsafe_b64decode now has padded=False as its default: "Padding of input is no longer required by default." On 3.15.0:
>>> base64.b64decode("Zm9vYg", padded=False)
b'foob'
>>> base64.urlsafe_b64decode("Zm9vYg")
b'foob'
If your code also runs on older versions, keep add_padding, because older versions don't accept the keyword.
Go
Go keeps padded and unpadded decoding as separate encodings. encoding/base64 has StdEncoding and URLEncoding, which are padded, and RawStdEncoding and RawURLEncoding, which "omit padding characters". Each one rejects the other format:
_, err := base64.StdEncoding.DecodeString("Zm9vYg")
fmt.Println("Std on unpadded:", err)
_, err = base64.RawStdEncoding.DecodeString("Zm9vYg==")
fmt.Println("Raw on padded:", err)
Std on unpadded: illegal base64 data at input byte 4
Raw on padded: illegal base64 data at input byte 6
The error is a CorruptInputError, and the byte offset is where the decoder gave up. For JWT segments, use RawURLEncoding. If you don't know which form you'll get, strip trailing = with strings.TrimRight(s, "=") and decode with the Raw variant instead of guessing.
JavaScript
Browser atob follows the WHATWG forgiving-base64 decode algorithm. It strips one or two trailing = only when the length is a multiple of 4, and fails on a remainder of 1. Unpadded input works. Wrong padding doesn't. Running this in Node 23.9:
atob("Zm9vYg"); // 'foob'
atob("Zm9vYg=="); // 'foob'
atob("Zm9vYg="); // InvalidCharacterError: Invalid character
The last one fails because a 7-character string isn't a multiple of 4, so the = is never stripped and counts as a character outside the alphabet. Node's Buffer.from(s, "base64") and Buffer.from(s, "base64url") both returned foob for the unpadded input.
The newer Uint8Array.fromBase64() lets you choose the behaviour. With its default lastChunkHandling: "loose" it accepts a final chunk of 2 or 3 characters, and with "strict" it requires the padding and throws a SyntaxError without it. MDN lists it as Baseline since September 2025. The Node 23.9 we tested with doesn't have it, so these options are taken from MDN rather than run here.
The bits padding leaves behind
Go back to "f" encoded as Zg==. The g carries two real bits and four zero bits. Change those four bits and you get Zh==, Zi== and so on, and a lenient decoder turns every one of them into "f". RFC 4648 section 3.5 says encoders must set these bits to zero and that decoders "MAY" reject input where they aren't.
That matters if you compare or hash base64 strings rather than the decoded bytes, for example when a signature, cache key or deduplication check uses the encoded form. Two different strings can decode to the same bytes. Both languages above have a strict mode for this:
Python b64decode("Zh==") -> b'f'
Python b64decode("Zh==", canonical=True) -> binascii.Error: Non-zero padding bits
Go StdEncoding.DecodeString("Zh==") -> "f"
Go StdEncoding.Strict().DecodeString -> illegal base64 data at input byte 2
canonical=True is new in Python 3.15. Go's Strict() has been there since Go 1.8, though its docs point out that it still ignores newline characters, so the input isn't fully canonical. The simpler fix is to decode first and compare or sign the bytes. Then the padding and the leftover bits no longer matter.
No comment for this article.