Base64 encode and decode

Convert text to Base64 and back. Handles emoji and every language correctly.

This tool runs in your browser. We never send what you type or paste to a server.

What is Base64?

Base64 represents binary data using 64 safe characters (A–Z, a–z, 0–9, + and /, with = for padding). It's used to put binary data into text formats like JSON, email and data URLs. Every 3 bytes become 4 characters, so encoded data is about 33% bigger.

Base64 is encoding, not encryption: anyone can decode it.

URL-safe Base64

Standard Base64 uses + and /, which have special meanings in URLs. The URL-safe variant (RFC 4648 §5), used by JWTs, replaces them with - and _ and usually drops the = padding. Tick URL-safe to use it.

Example

Hello, world!  →  SGVsbG8sIHdvcmxkIQ==
café           →  Y2Fmw6k=

Text is encoded as UTF-8 first, which is why café becomes five bytes and eight Base64 characters. The = at the end is padding to make the length a multiple of four.

How Base64 turns bytes into text

Base64 reads the input three bytes (24 bits) at a time and cuts those bits into four groups of six. Each 6-bit number, 0 to 63, picks one character from the alphabet A–Z (0–25), a–z (26–51), 0–9 (52–61), then + and /. The text Man shows it:

M        a        n
01001101 01100001 01101110      the 24 bits
010011 010110 000101 101110     cut into four 6-bit groups
  19     22      5     46
   T      W      F      u       → TWFu

When the input does not divide into threes, the last group is filled with zero bits and = marks the missing bytes: Ma becomes TWE= and M becomes TQ==. So padded output is always 4 × ⌈n ÷ 3⌉ characters long, and there are never more than two =. Base64 works on bytes, not characters: text is turned into bytes first, and this tool always uses UTF-8 for that.

Base64url in detail (RFC 4648 section 5)

RFC 4648 defines two alphabets that differ only in the last two characters. Standard Base64 uses + and /; Base64url, the “URL and filename safe” alphabet of section 5, uses - and _, because + means a space in form-encoded query strings and / separates path segments and is not allowed in file names. The other 62 characters and the bit layout are identical, so converting is a character swap:

subjects?_d   standard   c3ViamVjdHM/X2Q=
              base64url  c3ViamVjdHM_X2Q

The RFC lets padding be skipped when the length is known some other way, and most formats that use Base64url do skip it: JSON Web Tokens (RFC 7515 requires no padding), WebAuthn, and PKCE code_challenge values in OAuth. Leave the = off when the receiver expects that, since a literal = in a URL may itself need escaping as %3D.

The decoder here accepts either alphabet, with or without padding, and ignores spaces and line breaks, so you can paste a JWT segment or a wrapped MIME block as it is.

Base64 and Base64url in JavaScript

In the browser, btoa() and atob() work on “binary strings” where each character stands for one byte. Pass them real text and they either throw or quietly encode the wrong bytes. Convert to UTF-8 bytes with TextEncoder first; the same functions also run in Node, Deno and Bun:

// Browser and Node alike: TextEncoder gives the UTF-8 bytes, btoa encodes them.
function toBase64(text) {
  const bytes = new TextEncoder().encode(text);
  let bin = '';
  for (const b of bytes) bin += String.fromCharCode(b);   // one character per byte
  return btoa(bin);
}
function fromBase64(b64) {
  const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}
const toBase64url = (text) => toBase64(text).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
function fromBase64url(s) {
  const b64 = s.replace(/-/g, '+').replace(/_/g, '/');
  return fromBase64(b64 + '='.repeat((4 - (b64.length % 4)) % 4));
}
console.log(toBase64('café'));                    // → Y2Fmw6k=
console.log(toBase64url('subjects?_d'));          // → c3ViamVjdHM_X2Q
console.log(fromBase64url('c3ViamVjdHM_X2Q'));    // → subjects?_d

The trap, shown below: é is within Latin-1, so btoa('café') does not fail but produces Y2Fm6Q==, which every UTF-8 decoder will reject or garble. A character above U+00FF, such as an emoji, makes it throw.

console.log(btoa('café'));                        // → Y2Fm6Q==   é sent as one Latin-1 byte, not UTF-8
try { btoa('tea ☕'); } catch (e) { console.log(e.name); }   // → InvalidCharacterError

For large inputs, build the binary string in chunks (as this tool does) rather than one character at a time. Newer browsers (Baseline 2025, see MDN) have this built in, Base64url included; not yet available in Node 24, so check support before relying on it:

new TextEncoder().encode('subjects?_d').toBase64({ alphabet: 'base64url', omitPadding: true })
// "c3ViamVjdHM_X2Q"
Uint8Array.fromBase64('c3ViamVjdHM_X2Q', { alphabet: 'base64url' })

In Node, Buffer does both alphabets directly; the 'base64url' encoding name exists since Node 14.18 and 15.7 (Node docs):

const s = 'subjects?_d';
console.log(Buffer.from(s).toString('base64'));                       // → c3ViamVjdHM/X2Q=
console.log(Buffer.from(s).toString('base64url'));                    // → c3ViamVjdHM_X2Q
console.log(Buffer.from('c3ViamVjdHM_X2Q', 'base64url').toString());  // → subjects?_d
console.log(Buffer.from('Y2Fmw6k=', 'base64').toString('utf8'));      // → café

Python, the shell and PowerShell

Python's base64 module works on bytes, so encode the string first and decode the result to get a str:

print(base64.b64encode('café'.encode('utf-8')).decode('ascii'))   # → Y2Fmw6k=
print(base64.b64decode('Y2Fmw6k=').decode('utf-8'))               # → café

For Base64url, urlsafe_b64encode keeps the padding; strip it yourself, and add it back before decoding:

raw = b'subjects?_d'
print(base64.urlsafe_b64encode(raw).decode())                   # → c3ViamVjdHM_X2Q=
print(base64.urlsafe_b64encode(raw).rstrip(b'=').decode())      # → c3ViamVjdHM_X2Q
def b64url_decode(s):
    return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))    # put the padding back first
print(b64url_decode('c3ViamVjdHM_X2Q'))                         # → b'subjects?_d'

On Linux and in Git Bash, use printf rather than echo so no newline sneaks in. GNU coreutils' basenc --base64url keeps padding; tr works anywhere, including macOS, whose base64 has different options:

printf 'café' | base64                           # → Y2Fmw6k=
printf 'Y2Fmw6k=' | base64 -d; echo              # → café
echo 'café' | base64                             # → Y2Fmw6kK   echo's newline is encoded too
printf 'subjects?_d' | basenc --base64url                       # → c3ViamVjdHM_X2Q=
printf 'subjects?_d' | base64 | tr '+/' '-_' | tr -d '='        # → c3ViamVjdHM_X2Q
printf 'subjects?_d' | openssl base64 -A | tr '+/' '-_' | tr -d '='; echo   # → c3ViamVjdHM_X2Q
printf 'c3ViamVjdHM_X2Q==' | basenc --base64url -d; echo        # → subjects?_d

In Windows PowerShell, choose the text encoding explicitly. [Text.Encoding]::Unicode is UTF-16LE, which is what powershell -EncodedCommand expects but not what a web API wants:

[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Hello, world!'))       # → SGVsbG8sIHdvcmxkIQ==
[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('SGVsbG8sIHdvcmxkIQ=='))   # → Hello, world!
[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('hi'))               # → aABpAA==   UTF-16LE, not UTF-8
$b64 = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('subjects?_d'))
$b64.TrimEnd('=').Replace('+', '-').Replace('/', '_')                             # → c3ViamVjdHM_X2Q

Gotchas that cause wrong output

  • Line wrapping. GNU base64 wraps at 76 characters and openssl base64 at 64, as MIME and PEM do. A wrapped value pasted into JSON or a header breaks. Use base64 -w 0 or openssl base64 -A.
  • Missing padding in Python. b64decode and urlsafe_b64decode raise Incorrect padding on unpadded Base64url, which is how JWT segments arrive.
  • Silent clean-up in Python. Without validate=True, b64decode drops characters outside the alphabet, so bad input can decode to something instead of failing.
  • Wrong alphabet. atob() rejects - and _; swap them back to + and / first.
  • Text encoding. The same word gives different Base64 in UTF-8, UTF-16 and Latin-1. When two systems disagree, compare the bytes, not the strings.
try:
    base64.urlsafe_b64decode('c3ViamVjdHM_X2Q')
except ValueError as e:
    print(e)                                                    # → Incorrect padding
print(base64.b64decode('SGVs*bG8='))                            # → b'Hello'   the * is silently dropped
print(base64.b64decode('c3ViamVjdHM_X2Q=', altchars='-_'))      # → b'subjects?_d'
try:
    base64.b64decode('SGVs*bG8=', validate=True)
except ValueError as e:
    print(type(e).__name__)                                     # → Error   binascii.Error, a ValueError
head -c 100 /dev/zero | base64 | wc -l           # → 2     GNU base64 wraps lines at 76 characters
head -c 100 /dev/zero | base64 -w 0 | wc -c      # → 136   one line, no newline

Questions

Why does my decoded text look garbled?

The original was probably binary data (like an image) rather than text, or it used a different character encoding than UTF-8.

Is Base64 secure?

No. It's an encoding anyone can reverse. Never use it to hide passwords or secrets.

Can I decode a data: URI?

Yes. Paste the whole thing, including data:image/png;base64, and the prefix is removed for you. If the result is an image you get a preview and a download button.

How do I Base64url-encode a string in JavaScript?

In Node, use Buffer.from(text).toString('base64url'). In the browser, encode the text to UTF-8 bytes with TextEncoder, turn the bytes into a binary string, call btoa, then replace + with -, / with _ and remove the trailing = signs. Recent browsers also offer Uint8Array.prototype.toBase64 with alphabet: 'base64url' and omitPadding: true.

Why does btoa throw an InvalidCharacterError?

btoa only accepts characters with codes up to 255, one per byte. Emoji and most non-Latin text are above that. Encode the string to UTF-8 bytes with TextEncoder first and pass btoa a string made of those bytes.

Do I need the = padding?

Only if the receiving software requires it. Padding carries no data; it just makes the length a multiple of four. JWTs and most Base64url uses leave it out, while MIME email and many standard Base64 decoders expect it. This tool decodes either form.

Why is my Base64 different from another tool's?

Usually a trailing newline (echo adds one), a different text encoding (PowerShell's Unicode is UTF-16), line wrapping, or the URL-safe alphabet. Decode both results and compare the bytes to see which.