Base64

Base64 is a binary-to-text encoding that writes bytes with 64 printable characters: three bytes become four characters, so data grows by a third. This page has the alphabet table, padding rules, RFC 4648 test vectors, variants and common uses.

What is Base64?

Base64 is a binary-to-text encoding that represents any sequence of bytes using 64 printable ASCII characters. It exists so that binary data, such as an image, a key or a signature, can pass through systems that only handle text: email, JSON, XML, URLs and HTTP headers. The output is about a third larger than the input, and anyone can reverse it, since it has no key.

The idea is to take three bytes at a time, 24 bits, and write them as four groups of six bits. Each six-bit value from 0 to 63 is mapped to one character of a fixed alphabet. The reverse process reads four characters and recovers three bytes. The standard definition is in RFC 4648, which also defines the URL-safe variant, Base32 and Base16.

Four bytes in hex and in Base64The bytes DE AD BE EF are eight hex digits, one pair per byte, and the Base64 text 3q2+7w==, where three bytes make four characters and the fourth byte starts a new group.bytes11011110101011011011111011101111hexDEADBEEFBase643q2+7w==bytes 1–3 → characters 1–4 · byte 4 → characters 5–6 and padding
4 bytes are 8 hex digits or 8 Base64 characters. Hex aligns with bytes; Base64 aligns with groups of three, so the two strings cannot be compared by position.

The Base64 alphabet

The standard alphabet has 64 characters, in this order: the 26 capital letters, the 26 lower case letters, the ten digits, then + and /. The position in the list is the six-bit value. The equals sign is not part of the alphabet; it is padding. The table lists every character with its value, eight to a row.

The standard Base64 alphabet: value and character
Values 0 to 7Values 8 to 15Values 16 to 23Values 24 to 31Values 32 to 39Values 40 to 47Values 48 to 55Values 56 to 63
0A8I16Q24Y32g40o48w564
1B9J17R25Z33h41p49x575
2C10K18S26a34i42q50y586
3D11L19T27b35j43r51z597
4E12M20U28c36k44s520608
5F13N21V29d37l45t531619
6G14O22W30e38m46u54262+
7H15P23X31f39n47v55363/

Some boundaries are useful to remember: A is 0, Z is 25, a is 26, z is 51, 0 is 52, 9 is 61, + is 62 and / is 63. Capital letters are therefore the first quarter and a very common start of Base64 text: a string that starts with A decodes to a byte whose top six bits are zero.

Padding with =

Because three bytes become four characters, input whose length is not a multiple of three leaves a short last group. The encoder pads the output with = until its length is a multiple of four. If one byte is left, two characters carry its eight bits (six plus two, with four unused bits) and two = follow. If two bytes are left, three characters carry the sixteen bits and one = follows. The padding adds no information and the decoder can work out the same thing from the length.

Base64 paddingThe last group of input can hold 3, 2 or 1 bytes. Man encodes to TWFu; Ma encodes to TWE=; M encodes to TQ==.Man4D 61 6ETWFu3 bytes: no paddingMa4D 61TWE=2 bytes: one =M4DTQ==1 byte: two =
Padding keeps the output length a multiple of 4. The = signs carry no data; they only say how many bytes the last group had.

The unused bits in the last character are set to zero by an encoder. A strict decoder rejects a string in which they are not zero, because it was not produced by a normal encoder, and a lenient one ignores them. This is why different decoders sometimes give different results on hand-edited strings.

A worked case with padding: the two bytes Ma

The bytes 4D and 61 are the text Ma. Their 16 bits, 01001101 01100001, are cut into six-bit groups from the left: 010011, 010110 and 0001. The last group has only four bits, so the encoder adds two zero bits to make 000100. The values are 19, 22 and 4, and the alphabet gives T, W and E. Three characters carry 16 bits of data, so one = fills the group to four, and the output is TWE=.

Decoding reverses it. T, W and E are 19, 22 and 4, written in six bits as 010011, 010110 and 000100. Eighteen bits come out, and the decoder keeps the first sixteen as two bytes and discards the last two zero bits. The discard is the reason a correct encoder always writes zeros there: any other value would be silently lost, and two different strings could stand for the same data.

Output size: the formulas

For n input bytes, padded Base64 has 4 × ⌈n ÷ 3⌉ characters. Without padding it has ⌈4n ÷ 3⌉. A decoder works the other way: from a padded string of length L with p equals signs, the data is 3L ÷ 4 − p bytes. MIME wrapping adds two characters (CR and LF) per line of 76, so a wrapped string is about 2.6 percent longer than the unwrapped one.

Length of the Base64 for common data sizes
DataBytesPadded Base64Unpadded
A 128-bit key or UUID162422
A SHA-256 digest324443
A SHA-512 digest648886
A 1 KiB file102413681366
A 1 MiB file104857613981041398102

The unpadded column makes a point about the = signs: they account for at most two characters, so for anything beyond a few bytes, padding changes the length by a negligible amount, and the size of Base64 is determined by the four-for-three rule.

Base64 support in programming languages

Every mainstream language has Base64 in its standard library or its main ecosystem package. The names differ, and the URL-safe variant and padding handling are the usual places where behavior differs from one language to the next.

Base64 functions by language
LanguageEncode and decodeURL-safe variant
Pythonbase64.b64encode, base64.b64decodebase64.urlsafe_b64encode
JavaScript (browser)btoa, atob (Latin-1 only)Replace + and / by hand
JavaScript (Node.js)Buffer.from(x, 'base64')'base64url' encoding
Javajava.util.Base64.getEncoder, getDecodergetUrlEncoder, getUrlDecoder, getMimeEncoder
C#Convert.ToBase64String, FromBase64StringReplace + and / by hand (or WebEncoders)
Goencoding/base64: StdEncodingURLEncoding, RawURLEncoding (no padding)
PHPbase64_encode, base64_decodeReplace + and / by hand
SwiftData.base64EncodedString()Replace + and / by hand
RustThe base64 crate (not in std)URL_SAFE engines in the crate

The browser pair deserves a warning. btoa and atob treat strings as sequences of bytes, one per character, and fail on any character above U+00FF. Correct handling of text goes through UTF-8 first, as the pages on encoding and decoding show.

Variants outside RFC 4648

Several schemes borrow the idea with other alphabets. The password hash bcrypt writes its salt and hash with an alphabet that starts with . and / and then A–Z a–z 0–9, the same sixty-four symbols in a different order, and the Unix crypt scheme used a similar one. IMAP mailbox names use a modified UTF-7 in which the Base64 uses a comma in place of /. OpenPGP wraps binary messages in ASCII armor, which is Base64 with a 24-bit checksum line added at the end.

These are not interchangeable with the standard form. A string produced with the bcrypt alphabet decodes to the wrong bytes in a standard decoder without any error, because every character is a valid symbol. When the source documentation names an unusual alphabet, use the library of that system rather than a general Base64 tool.

Denser encodings: Base85 and beyond

If the aim is to put bytes into text with as little growth as possible, a larger alphabet helps. Ascii85, used in PostScript and PDF, writes four bytes as five characters from 85 symbols, a growth of 25 percent against Base64's 33. Z85 and Base91 follow the same idea with other alphabets. The cost is that the larger alphabets include characters that are special in JSON, XML and URLs, so they need escaping in exactly the places where Base64 was chosen to avoid it.

That is why Base64 remains the default. A difference of eight percentage points in size seldom outweighs the benefit of a format that every language, tool and person already knows, and whose alphabet passes through email, JSON and URLs untouched.

Common misunderstandings

Security notes for programmers

Decoding untrusted Base64 is routine and mostly safe, but a few rules apply. Limit the decoded size before allocating memory, because a short string cannot expand more than three quarters of its length, yet a huge one can still exhaust memory. Validate the decoded content against what you expect: a field declared as an image should begin with an image signature. Accept one canonical form where equality matters, since signatures and hashes computed over Base64 text, not over bytes, can be bypassed with a non-canonical string that decodes to the same data.

For secrets, note that ordinary decoders use table lookups and branches that depend on the data, which can leak information through timing. Libraries that handle keys, such as libsodium, provide constant-time Base64 routines for this reason. For everyday data, which includes anything on this site, the standard functions are appropriate.

Test vectors from RFC 4648

The RFC lists seven examples that every implementation is checked against. They are the shortest way to confirm that an encoder handles all three padding cases, and the values below are generated by this site's own encoder, which passes them in its test suite.

RFC 4648 section 10: Base64 test vectors
Input textBase64
(empty)(empty)
fZg==
foZm8=
fooZm9v
foobZm9vYg==
foobaZm9vYmE=
foobarZm9vYmFy

Variants of Base64

The name covers a family. The core mapping is the same, and the variants change the last two alphabet characters, the padding rule or the layout. They exist because each environment forbids different characters.

Base64 variants and where they come from
VariantLast two charactersPaddingLayoutTypical use
Standard (RFC 4648 §4)+ /RequiredOne stringJSON, XML, data URIs
URL and filename safe (RFC 4648 §5)- _Often omittedOne stringJWTs, URL parameters, file names
MIME (RFC 2045)+ /RequiredLines of at most 76 characters, CRLFEmail attachments
PEM (RFC 7468)+ /RequiredLines of 64 characters between BEGIN and ENDCertificates and keys

Decoders differ in strictness. Some reject whitespace, some reject missing padding, some accept both alphabets. The decoder on this site accepts both alphabets, whitespace and missing padding, and reports what it forgave. It is also worth knowing that Base64 is not a numeric base conversion: the string for a number's bytes is not the number written in base 64, a distinction the hex converter page explains.

Where Base64 is used

Common uses of Base64
WhereWhat is encodedExample or note
Email (MIME)Attachments and non-ASCII bodiesContent-Transfer-Encoding: base64, lines of 76 characters
Data URIsSmall images, fonts and files in HTML and CSSdata:image/png;base64,iVBORw0K…
JSON Web TokensHeader and payloadURL-safe alphabet, no padding
HTTP Basic authenticationuser:passwordAuthorization: Basic dXNlcjpwYXNz
Certificates and keysDER bytesPEM files, 64-character lines
APIs and databasesBinary fields in JSON or XMLImages, PDFs, signatures
Subresource IntegrityHash of a script or styleintegrity="sha384-…"
Package lock filesHash of a packagenpm lock files use sha512- followed by Base64

Each of these has a page that shows the specifics: decode and encode for text, images and PDFs for files, and hex for hashes and keys.

Base64 compared with hex and Base32

Hex, Base32 and Base64 do the same job at different densities. The more symbols in the alphabet, the fewer characters per byte, and the more care is needed in reading and typing them. Hex is the easiest to read byte by byte and the longest; Base64 is the shortest and distinguishes upper from lower case.

Three byte-to-text encodings in RFC 4648 terms
EncodingAlphabet sizeBits per characterCharacters per byteCase-sensitive
Base16 (hex)1642No
Base323251.6No (upper case by default)
Base646461.33Yes

Base32 exists for places where case is lost, such as file names on some systems and codes that people read aloud, and it avoids look-alike symbols in its alphabet. The comparison with hex is worked through on the hexadecimal page, and the two forms convert into each other through the bytes.

Recognizing Base64 when you see it

A pattern for it in code is ^(?:[A-Za-z0-9+/]4)*(?:[A-Za-z0-9+/]2==|[A-Za-z0-9+/]3=)?$, which accepts padded standard Base64 only. It also accepts non-canonical strings whose spare bits are not zero, and it matches many ordinary words, so it filters candidates and proves nothing. Use it to reject text that cannot be Base64, then decode and check the result.

A string is plausibly Base64 if every character is a letter, digit, + or / (or - and _), it has no spaces apart from regular line breaks, its length is a multiple of four (counting = signs), and any = signs are only at the end, at most two. Those tests also match plenty of ordinary words and identifiers, so they are a necessary and not a sufficient check: the word encode followed by a number passes. The strongest test is to decode it and see whether the result means something.

Prefixes help with files. A string starting with iVBOR is a PNG, /9j/ is a JPEG, JVBERi is a PDF, UEsD is a ZIP archive or Office document, R0lGOD is a GIF and UklGR is a WebP or other RIFF file. The auto decoder applies tests like these to hex and URL encoding as well.

Base64 is not encryption

Base64 is a reversible change of representation. It has no key, no secret and no work factor, and decoding needs one standard function. Treating it as protection is a repeated mistake in code review: secrets in configuration files stored as Base64, tokens that only look opaque, personal data masked by encoding. The accurate description is that Base64 is obfuscation at best, and the right tool for secrecy is encryption with a vetted algorithm.

Typing and reading Base64 by hand

The standard alphabet includes characters that look alike in many fonts: the digit 0 and the capital O, the digit 1, the capital I and the lower case l. For machine use it does not matter, but for values that people copy by eye or read aloud, it causes errors. Base58, used for Bitcoin addresses, drops 0, O, I and l and the two punctuation characters from the alphabet to avoid exactly that, at the price of not being a power of two and therefore needing arithmetic on the whole number to convert.

If a Base64 string has to be typed, as in a support call, prefer a font with distinct shapes, write it in monospace, and add a check: the length and the number of = signs at the end let the listener confirm that nothing was lost. Case also counts: a lower case l and an upper case L are different characters and different values (37 and 11).

Choosing between Base64 and the alternatives

Which encoding for which situation
SituationChoiceReason
Binary data inside JSON, XML or an emailBase64Standard, supported everywhere, compact enough
Token in a URL, cookie or file nameBase64URL without paddingNo characters that need escaping
Short value that people compare or typeHexReadable byte by byte, case-insensitive
Value read aloud or entered by handBase32 or Base58No look-alike characters, case-insensitive for Base32
Large binary files over HTTPRaw bytes, multipartNo size overhead
Smallest text form of binary dataBase8525 percent growth, but needs escaping

Standards and sources

RFC 4648 also gives the reasoning behind the design choices and a discussion of security considerations, including the warning about non-canonical encodings. The authoritative text is RFC 4648, The Base16, Base32, and Base64 Data Encodings, which defines both alphabets, the padding rule and the test vectors. MIME wrapping is specified in RFC 2045 and PEM text in RFC 7468. The data URI scheme is RFC 2397, and the way JSON Web Signatures use the URL-safe form without padding is in RFC 7515.

Base64 in databases and storage

Binary values stored as Base64 text take a third more space and cost a conversion on every read, so a binary column (bytea in PostgreSQL, BLOB or VARBINARY elsewhere) is the better home for them. When a text column is the only choice, Base64 is the compact one. Databases can convert in queries: PostgreSQL offers encode(data, 'base64') and decode(text, 'base64'), and MySQL has TO_BASE64 and FROM_BASE64. Both also convert to hex (encode(data, 'hex') and HEX), which is how a digest stored as Base64 can be compared with a hex value in a query.

A short history

Encodings of binary into printable text predate the web. The Unix uuencode format did it for mail between machines in the 1980s. Privacy Enhanced Mail, in RFC 989 (1987), defined an encoding with a 64-character alphabet and = padding, which became the basis of the PEM file format still used for certificates. The MIME standard in the early 1990s named the encoding Base64 and added the 76-character line limit for email. RFC 4648 (2006) collected the variants and gave the URL-safe alphabet its definition, and it is the reference most libraries follow today.

Tools for working with Base64

The converters on this site cover the common jobs. Base64 decode and Base64 encode work on text and files. Base64 to image and image to Base64 handle pictures and data URIs. Base64 to PDF checks and previews a PDF. Base64 to hex converts hashes and keys. All of them run in the browser, and the tools page lists them with the hex converters.

Questions about Base64

What does Base64 stand for?

It names the number of symbols in its alphabet: 64. Each symbol carries six bits, and the encoding writes any sequence of bytes using only those 64 printable characters plus = for padding.

Why does Base64 make data about 33% larger?

Three bytes (24 bits) become four characters. Each character is stored in one byte of text, so 3 bytes of data turn into 4 bytes of text, an increase of one third. Padding and line breaks add a little more.

Is Base64 safe for passwords?

No. Base64 is not a security measure. It can be decoded by anyone and has no key. Credentials written in Base64, such as in a Basic authentication header, are as visible as plain text and must travel over an encrypted connection.

Can two different strings decode to the same bytes?

Yes, in lenient decoders. The last character of a padded string has unused bits. Zm8= is the canonical Base64 of fo (66 6F), and Zm9= decodes to the same two bytes if the spare bits are ignored. Strict decoders reject Zm9= because those bits are not zero. Encoders always produce the canonical form.

What is the difference between Base64 and Base64URL?

Base64URL uses - and _ in place of + and / so it is safe in URLs and file names, and it usually leaves out the = padding. The two encodings carry the same data in the same way.