Base64 vs Base64URL

发布于

本指南内容

Standard Base64 uses + and / and usually = padding. Base64URL (RFC 4648 §5) uses - and _ and often omits padding so strings survive in URLs and JWTs.

Mixing the two causes decode errors. Convert deliberately before you paste into APIs or tokens.

Use our Base64URL encoder/decoder and JWT tool to verify values without uploading them.

接着试用这些私密工具

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 padding or silently wrong bytes.
  • Java: IllegalArgumentException: Illegal base64 character 2d (2d is -).
  • .NET: FormatException: The input is not a valid Base-64 string.
  • JavaScript: atob throws InvalidCharacterError.
  • 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.

常见问题

Which one do JWTs use?

JWT header and payload segments use Base64URL without padding.

How do I convert Base64 to Base64URL?

Replace + with -, / with _, and strip = padding. Or use the Base64URL tools on this site.

相关工具和指南

评论 (0)

对“Base64 vs Base64URL”有疑问、想法或发现了 bug?欢迎留言评论、为工具评分或回复他人。

暂无评论,快来分享您的反馈吧!

发表评论

为此工具评分:
Esc
↑ ↓ 移动↵ 打开Esc 关闭