The question “why does my Base64 fail to decode?” has a very common answer: it is actually Base64URL. Here is how to tell them apart and convert between them.
The differences
| Base64 | Base64URL | |
|---|---|---|
| Character 62 | + |
- |
| Character 63 | / |
_ |
Padding = |
Required | Usually omitted |
| Safe in URLs and file names | No | Yes |
| Typical use | Data URIs, e-mail, JSON | JWT, OAuth, URL parameters |
Everything else — the algorithm and the other 62 characters — is identical, so most values look the same. A value is only distinguishable if it happens to contain one of the four special characters.
Symptoms of a mix-up
- Python:
binascii.Error: Incorrect paddingor silently wrong bytes. - Java:
IllegalArgumentException: Illegal base64 character 2d(2dis-). - .NET:
FormatException: The input is not a valid Base-64 string. - JavaScript:
atobthrowsInvalidCharacterError. - PHP strict mode returns
false.
Conversion code
JavaScript
const urlToStd = (s) => s.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(s.length / 4) * 4, '=');
const stdToUrl = (s) => s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
Python
base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
PHP
base64_decode(strtr($s, '-_', '+/'), true);
Go
base64.RawURLEncoding.DecodeString(s)
Which one should you use?
- Putting the value in a URL, cookie, file name or token: Base64URL without padding.
- Embedding in HTML, CSS, JSON, XML or e-mail: standard Base64, because that is what data URIs and MIME require.
- Designing an API: accept both on input, document exactly one on output.
Our Base64 decoder accepts both automatically. To convert explicitly, use the Base64URL encoder, the Base64URL decoder or normalization.
Comments (0)
Questions, ideas or a bug in “Base64 vs Base64URL”? Leave a comment, rate the tool, or reply to others.
No comments yet. Be the first to share your feedback!