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.
댓글 (0)
“Base64 vs Base64URL”에 대한 질문, 아이디어, 버그가 있으신가요? 댓글을 남기거나 도구를 평가하거나 다른 사람에게 답글을 달아 주세요.
아직 댓글이 없습니다. 첫 번째로 의견을 남겨 주세요!