Skip to content

Binary-to-Text Encoding: Base64, Base32, Hex, Percent-Encoding, Data URIs ​

"Base encoding visually hides otherwise easily recognized information, such as passwords, but does not provide any computational confidentiality." — S. Josefsson, RFC 4648, The Base16, Base32, and Base64 Data Encodings, Security Considerations (October 2006)

Summary: A binary-to-text encoding turns arbitrary bytes into a restricted alphabet of printable characters so they can travel through channels that only carry text; it costs size, it never adds secrecy, and every boundary (URL, JSON, header, e-mail, HTML) has its own variant and its own bugs. Focus: Hex, Base64 and base64url, Base32 (Crockford, z-base-32), Base58, Base85, percent-encoding and the + versus %20 trap, IRIs and Punycode, data URIs, quoted-printable, HTML and JSON escaping, how Go, PHP, JavaScript and Laravel behave, and the classic bugs. Learning goal: Pick the right encoding for each boundary, predict its size, decode untrusted input safely, recognise a Base64 value in a JWT, a Kubernetes Secret or an Authorization header, and fix the "plus became a space" bug in under a minute.

This page is the complete reference for the encodings that sit between raw bytes and text channels. It owns the encodings themselves and their pitfalls. It does not re-teach what a byte or UTF-8 is (Bits, Bytes & Text Encoding), how structured data is laid out (Serialization Formats), how to shrink data (Compression), how to fingerprint it (Checksums & Hashing), how to protect it (Cryptography Fundamentals), how tokens are signed (Password Hashing & Signed Tokens) or how DNS resolves the Punycode names this page produces (DNS Resolution for Developers). The Go API walkthrough lives in JSON, XML, Struct Tags, Encoder/Decoder, Base64; this page shows only what each encoding needs.

Page map ​

If you are looking forGo to
One table to memorise: encoding, alphabet, size cost, where it is usedEverything in one minute
Why bytes cannot just be pasted into JSON, URLs or headersWhy it exists
uuencode, MIME, RFC 4648, RFC 3986, Punycode, JWSWhere it comes from
Hex and Base16Hex
6-bit groups, alphabet, = padding, 33% overhead, 76-column linesBase64, Padding
- and _, padding in URLs, JWT segmentsBase64url
Why two libraries disagree on the same stringDecoding leniency
TOTP secrets, Crockford, z-base-32, base32hexBase32
Bitcoin addresses, no 0OIlBase58
Ascii85, git binary patches, PDFBase85
Reserved vs unreserved, UTF-8 bytes, %XXPercent-encoding
+ vs %20, double encoding, path vs query vs fragmentPlus vs space, Double encoding, Components
Persian characters in URLs and domains, IDNAIRI and Punycode
HTML entities, JSON string escapesHTML and JSON
data: URLs, size, CSPData URIs
MIME bodies and headersQuoted-printable, uuencode
"It is encoded, so it is safe"Not encryption
JWT, Kubernetes Secrets, Basic auth, src, Git LFS, ProtobufWhere each one shows up
Go, PHP, JavaScript, Laravel, CLI tools side by sidePer-language behaviour
Bit math, lengths, speed, error messagesMechanics
Code for every classic bugSolving the classic problems
Which encoding for which jobChoosing
Monolith to distributed systemsIn architecture
Symptom to causeTroubleshooting
Hands-onLab
Wrong beliefs, cheat sheet, definitionsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The encodings. Every row is unpacked in the catalogue. Ratios are encoded size divided by input size, measured on this machine for a 17-byte Persian string where noted.

EncodingAlphabetOutput sizeTypical home
Hex / Base160-9A-F (or lower case)2.00xHashes, colours, byte dumps, UUIDs, Laravel signature
Base64A-Z a-z 0-9 + /, pad =4 chars per 3 bytes, about 1.33x (1.37x with MIME lines)JSON, XML, e-mail, Authorization: Basic, Kubernetes Secrets, data URIs
Base64 raw (unpadded)same, no =about 1.33xCompact tokens
Base64urlA-Z a-z 0-9 - _about 1.33xJWT, URL parameters, cookies, filenames
Base32A-Z 2-7, pad =8 chars per 5 bytes, 1.6xTOTP secrets, case-insensitive systems
Crockford / z-base-32no ILOU, or a shuffled alphabet1.6xHuman-typed IDs, ULID
Base58no 0 O I l + /about 1.37xBitcoin addresses, short IDs
Base85 / Ascii8585 printable characters5 chars per 4 bytes, 1.25xPDF, PostScript, git binary patches
Percent-encoding%XX per byte1x to 3x (3x for each non-unreserved byte)URLs, forms
Quoted-printablemostly literal, =XX otherwise1x to 3xMIME text bodies and headers
HTML entities / JSON escapes&, \n, \uXXXXdepends on contentHTML text, JSON strings
Punycodexn-- + ASCIIabout 1xInternationalized domain names

The three things to remember.

SituationDo this
Putting bytes in a URL, cookie, filename or JWTbase64url without padding, and still percent-encode if the value goes in a query string you build by hand
Putting bytes in JSON, XML or e-mailstandard Base64; expect +33%
Someone says "it is encoded, so it is safe"It is not. Base64 is a reversible spelling, not a lock (Not encryption)

Why it exists ​

Computers move bytes, but many of the pipes were built to move text. E-mail in 1980s Internet was 7-bit US-ASCII with lines of limited length; a stray byte of value 0 or a line made only of a dot could end or corrupt a message. JSON strings must be valid Unicode and cannot hold a raw byte 0xFF. A URL has a small set of legal characters and a handful that mean "structure". An HTTP header is a line of text; a cookie value excludes space, quote, comma, semicolon and backslash. An environment variable is a C string and stops at the first zero byte. YAML and .env files are for people to read. RFC 4648 states the original motivation: base encoding is used "to store or transfer data in environments that, perhaps for legacy reasons, are restricted to US-ASCII data", and "can also be used in new applications that do not have legacy restrictions, simply because it makes it possible to manipulate objects with text editors."

A binary-to-text encoding is the agreement that makes this safe: pick an alphabet every channel treats as plain data, and map bytes to it reversibly. The price is size, and the fundamental trade-off is between how restricted the alphabet is and how many bytes you waste.

Bigger alphabet (fewer characters)Smaller alphabet (more characters)
Base85: 1.25x, but uses quotes, backslash, angle bracketsHex: 2x, but only 0-9a-f, the safest alphabet there is
Base64: 1.33x, but +, /, = are special in URLsBase32: 1.6x, but case-insensitive and typeable
Shorter outputSurvives more channels, fewer escaping rules
Needs a second layer when a delimiter is in the alphabetWorks almost everywhere unchanged

The analogy we reuse on this page: a courier who only accepts printed letters. You want to ship a brick. The courier will not carry a brick, only paper. So you write a letter that describes the brick one small piece at a time, in a fixed alphabet; the receiver reads the letter and rebuilds the brick. Nothing about the letter hides the brick: anyone who reads the letter can rebuild it. Different couriers accept different letters (a courier for URLs refuses letters containing /; one for e-mail wants lines under 76 characters), so you must know which courier you are using.

Three common misunderstandings, up front ​

  1. "Base64 makes data safe or secret." It makes data transportable. Anyone can reverse it with one command. Never use it for passwords, tokens meant to be hidden, or "obfuscating" an API key.
  2. "Base64 is one thing." There are at least four spellings that all call themselves base64: standard padded, standard unpadded, base64url padded, base64url unpadded, plus MIME-wrapped. A value from one will fail or silently corrupt in a decoder expecting another.
  3. "URL encoding is one thing." %20 is correct in a path and in RFC 3986; + for a space is only correct in application/x-www-form-urlencoded (HTML forms and query strings read as forms). Mixing them is the most common encoding bug on the web.

Where it comes from ​

YearEventSource
1980uuencode/uudecode written by Mary Ann Horton at UC Berkeley so binary files could pass through e-mail and UsenetWikipedia (secondary source; not verified against a primary text)
1996MIME (RFC 2045, November 1996) defines the Content-Transfer-Encoding header with the Base64 and quoted-printable encodings, and the 76-character line limitRFC 2045
1998data: URL scheme (RFC 2397, August 1998), "only useful for short values"RFC 2397
2003Punycode (RFC 3492, March 2003) for Internationalized Domain Names in ApplicationsRFC 3492
2003 to 2006RFC 3548 (July 2003) then RFC 4648 (October 2006) standardise Base16, Base32, Base64 and add the URL and filename safe alphabetRFC 3548, RFC 4648
2005RFC 3986 (January 2005) defines URI syntax, reserved and unreserved characters and percent-encoding; RFC 3987 (January 2005) adds IRIsRFC 3986, RFC 3987
2015JSON Web Signature (RFC 7515, May 2015) fixes JWT segments as base64url without padding; RFC 7617 (September 2015) defines Basic auth as Base64 of user:passwordRFC 7515, RFC 7617
2025 to 2026JavaScript gains native Uint8Array.prototype.toBase64 and toHex; Node 26 on this machine reports both as functionsobserved with node -e (Node v26.10.0)

Two pieces of vocabulary matter for the rest of the page. RFC 4648 calls the 6-bit regrouping a quantum (the final partial input group is the "final quantum"), and RFC 3986 calls the %XX form a pct-encoded octet: pct-encoded = "%" HEXDIG HEXDIG. The WHATWG URL Standard is what browsers actually implement; where it disagrees with RFC 3986 (for example + for space in forms), this page says so.

3 input bytes = 24 bits = 4 groups of 6 bits = 4 output characters0100110101100001011011100x4D 'M'0x61 'a'0x6E 'n'010011= 19alphabet[19]T010110= 22alphabet[22]W000101= 5alphabet[5]F101110= 46alphabet[46]u1 byte left over: 2 chars + "==" · 2 bytes left over: 3 chars + "=" · output length = 4 x ceil(n / 3)Base64url swaps "+" (62) and "/" (63) for "-" and "_" and usually drops the "=".

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, the precise definition, a short timeline, real scenarios, which product does what, and a fix that links to the code in Solving the classic problems.

Hex / Base16 Must-know ​

In plain words: write every byte as two characters from 0-9 and a-f. The byte 0xD8 becomes the text d8.

Common misunderstanding: "Hex is for numbers." It is the cheapest way to show any bytes: one byte is always exactly two characters, so you can read offsets by eye and no byte can be mistaken for structure. Upper and lower case are the same value; RFC 4648 says Base16 is the "standard case-insensitive hex encoding" and needs no padding because "a full code word is always available".

Definition: Base16 (RFC 4648 section 8) maps each 4-bit nibble to one of 0123456789ABCDEF; two nibbles make a byte; the output is exactly 2x the input.

text
input bytes      4d 61 6e              "Man"
as hex           4d616e                (6 chars for 3 bytes)
upper-case       4D616E                same value
persian "سلام"   d8b3 d984 d8a7 d985   (8 bytes in UTF-8, 16 hex chars)

Real scenarios: SHA-256 digests printed as 64 hex characters; CSS colours #1e90ff; UUIDs (32 hex digits with dashes); xxd and hexdump output; MAC addresses; Laravel's signed-URL signature parameter; Go's %x verb; Git object IDs; protocol debugging in Wireshark.

ProductHex helpersCase
Goencoding/hex (EncodeToString, DecodeString, Dump), fmt %xEncodes lower case; decodes both
PHPbin2hex, hex2bin, dechexbin2hex lower case; hex2bin accepts both
JavaScriptUint8Array.prototype.toHex (a function in Node 26 here), Buffer.toString('hex')lower case
PostgreSQLencode(bytea, 'hex'), \x input formatlower case
CLIxxd, xxd -p, hexdump -C, openssl dgstlower case

Fix / how to use it: compare digests case-insensitively and in constant time; never compare hex strings with a plain == when they are secrets. Go: encodings. PHP: hash_equals(strtolower($a), strtolower($b)).

Base64 Must-know ​

In plain words: cut the bytes into pieces of 6 bits and write each piece as one character from a 64-letter alphabet. Three bytes (24 bits) become exactly four characters.

Common misunderstanding: "The = signs are part of the data." They are filler that makes the length a multiple of 4. The data is only in the letters.

Definition (RFC 4648 section 4): the alphabet is A-Z (0 to 25), a-z (26 to 51), 0-9 (52 to 61), + (62), / (63), and = is the pad. Three input bytes make a 24-bit group, split into four 6-bit values, each an index into the alphabet. Output length for n input bytes is 4 * ceil(n / 3), about 1.33 * n.

text
bytes   M=0x4D      a=0x61      n=0x6E
bits    01001101    01100001    01101110
6-bit   010011 010110 000101 101110
value   19     22     5      46
char    T      W      F      u        -> "TWFu"

Real scenarios: an image inside a JSON API response; a PDF attachment in an e-mail; a TLS certificate in PEM files; an SSH public key; a Kubernetes Secret value; a Docker config auth field; the Authorization: Basic header; an HTML img with a data: URL; a Protobuf bytes field rendered as JSON.

ProductStandard encoderOutput has line breaks?
Go encoding/base64StdEncodingNo (the decoder skips CR and LF)
PHPbase64_encodeNo
JavaScript browserbtoa (binary string only), Uint8Array.toBase64()No
Node.jsBuffer.from(x).toString('base64')No
Pythonbase64.b64encodeNo (encodebytes adds \n every 76)
GNU coreutils base64wraps at 76 by default; -w 0 disablesYes
macOS base64no wrapping by default (measured here)No
openssl base64wraps at 64; -A for one lineYes
JavaBase64.getEncoder() plain, getMimeEncoder() 76 with CRLFOnly for MIME

Fix / how to use it: always tell the other side which base64 you used (standard, url-safe, padded, wrapped). In APIs, document it in the schema. Code: encodings.

Padding, raw and unpadded Base64 Important ​

In plain words: when the input length is not a multiple of 3, the last group is short, and = characters fill the output up to a multiple of 4. Some systems drop the = because the decoder can work the missing length out.

Common misunderstanding: "Padding is required, so a string without it is broken." RFC 4648 section 3.2 says implementations "MUST include appropriate pad characters at the end of encoded data unless the specification referring to this document explicitly states otherwise", and JWS explicitly states otherwise. Both forms are legitimate; each decoder only accepts what it is configured for.

Definition: with 1 leftover byte the output is 2 characters plus ==; with 2 leftover bytes it is 3 characters plus =; with 0 leftover bytes there is no padding. Length of the unpadded form is ceil(4n / 3). The unpadded length modulo 4 is always 0, 2 or 3; a length that is 1 modulo 4 can never be valid.

text
input   "hi!"  3 bytes   -> aGkh     (no pad)
input   "hi"   2 bytes   -> aGk=     (1 pad)
input   "h"    1 byte    -> aA==     (2 pads)
unpadded forms           -> aGk   aA
decoder sees "aGk" and the length 3 mod 4 -> it knows exactly one '=' is missing

Real scenarios: a JWT that fails in one library because the library insists on =; a signature in a URL where = had to be percent-encoded as %3D; a hash stored with and without padding in two tables so lookups miss; a webhook secret copied with its = stripped by a chat app.

DecoderPadded inputUnpadded input
Go StdEncodingacceptedrejected (illegal base64 data)
Go RawStdEncodingrejectedaccepted
PHP base64_decode (also strict)acceptedaccepted (the php-src source says it accepts zero padding)
WHATWG atobacceptedaccepted unless length mod 4 is 1
Python b64decodeacceptedbinascii.Error: Incorrect padding
Node Buffer.from(s, 'base64')acceptedaccepted
Java Base64.getDecoder()acceptednot tested here (no JDK on this machine); check the Javadoc of your version

Fix: normalise at your boundary: decode with the variant you documented and re-pad or strip before comparing. See Solving the classic problems.

Base64url (URL- and filename-safe) Must-know ​

In plain words: the same encoding with + replaced by - and / replaced by _, usually with the = removed, so the result can sit in a URL or a filename without escaping.

Common misunderstanding: "base64url is a different algorithm." It is the same bit mapping with two characters swapped. RFC 4648 section 5 says: "This encoding may be referred to as 'base64url'. This encoding should not be regarded as the same as the 'base64' encoding and should not be referred to as only 'base64'."

Definition: the alphabet of Table 2 in RFC 4648: A-Z a-z 0-9 - _. RFC 4648 notes "The pad character '=' is typically percent-encoded when used in an URI, but if the data length is known implicitly, this can be avoided by skipping the padding". JWS fixes the form used by JWT: base64url "with all trailing '=' characters omitted ... and without the inclusion of any line breaks, whitespace, or other additional characters".

text
standard : ++++//4=            <- '+' becomes a space in a query string, '/' splits a path
base64url: ----__4             <- safe in a path, query, cookie, filename
JWT      : eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9 . eyJzdWIiOiI0MiJ9 . D7xYjF12...
             header (base64url)                      payload          signature

Real scenarios: the three segments of a JWT; the OAuth PKCE code_challenge (RFC 7636 defines BASE64URL-ENCODE); short links with random identifiers; opaque tokens in password-reset links; object keys derived from hashes.

Productbase64url API
Gobase64.URLEncoding, base64.RawURLEncoding (no padding)
PHPno built-in: rtrim(strtr(base64_encode($s), '+/', '-_'), '=')
JavaScript / NodeBuffer.toString('base64url'); Uint8Array.toBase64({alphabet: 'base64url'})
Pythonbase64.urlsafe_b64encode (pads)
JavaBase64.getUrlEncoder().withoutPadding()
PostgreSQLencode(x, 'base64url') appears in the PostgreSQL 19 documentation I read

Fix: pick base64url for anything that touches a URL, cookie or filename; reserve standard Base64 for bodies. Code: urlbug.

Binary bytes must travel as textWho/what reads it?A human types itBase32 (RFC 4648) / CrockfordA URL, cookie, filenamebase64url, no paddingJSON, e-mail, data URIstandard base64 (+33%)Hash or ID printed for debugging: hex (+100%)Can you avoid text? Use bytes (Protobuf, multipart)typed by peoplein mail / JSONin URL

Decoding leniency: the same string, different answers Important ​

In plain words: decoders differ in what they forgive: whitespace, newlines, a missing =, a stray character, the wrong alphabet, non-zero leftover bits.

Common misunderstanding: "If it decodes, it is valid." Some decoders silently drop characters they do not understand, so malformed or hostile input can decode to something shorter or different, which breaks signature checks and string comparisons.

Definition: RFC 4648 section 3.3 says "Implementations MUST reject the encoded data if it contains characters outside the base alphabet when interpreting base-encoded data, unless the specification referring to this document explicitly states otherwise", and MIME states otherwise ("be liberal in what you accept"). The WHATWG forgiving-base64 decode used by atob is a third policy: strip ASCII whitespace, drop one or two trailing = if the length is a multiple of 4, fail if the length mod 4 is 1, fail on any non-alphabet character.

text
Input "aGk"  decoded as standard base64:
  Go StdEncoding    -> error
  Go RawStdEncoding -> "hi"
  Python b64decode  -> binascii.Error: Incorrect padding
  PHP strict        -> "hi"
  atob / Node       -> "hi"
Input "-_-_" (url alphabet) decoded as standard:
  Go StdEncoding    -> error         Python b64decode -> b'' (silently empty)
  atob              -> InvalidCharacterError    Node Buffer -> bytes fbffbf (accepts both)

Real scenarios: a signature that verifies in one service and fails in another; a WAF that decodes a payload one way while the application decodes it another way (a classic bypass); a trailing newline in a Kubernetes Secret that makes a login fail; cache keys built from base64 that differ in padding.

BehaviourGoPHPWHATWG atob / browsersPythonNode BufferJava
Skips CR and LFYesYes (php-src: strict mode skips whitespace, non-strict skips every unknown character)Yes (all ASCII whitespace)Default yes; validate=True noYesBasic decoder rejects; MIME decoder ignores
Skips other junkNo (error)Non-strict: silently discards; strict: falseNo (error)Default: discards; validate=True: errorYes (measured: aG$k= decodes to hi)Basic: error (Javadoc: rejects characters outside the alphabet)
Accepts missing paddingOnly Raw*YesYes (unless length mod 4 is 1)NoYesYes
Accepts the other alphabetNoNoNob64decode no, urlsafe_b64decode accepts bothYes (both)No
Rejects non-zero trailing bitsOnly .Strict()NoNoNoNoNo

Fix: decode the one variant you specified, reject whitespace you did not expect, and verify signatures over the received string, not over a re-encoded value. Code: safedecode.

Base32 Important ​

In plain words: like Base64 but with only 32 characters (A-Z and 2-7), so each character carries 5 bits and 8 characters carry 5 bytes. It is longer, but it has no lower case, no +, no /, and no digits that look like letters.

Common misunderstanding: "Base32 is just a worse Base64." Its value is that it survives case-folding (DNS names, file systems on macOS and Windows) and is readable aloud. RFC 4648 gives the rationale: a form "that needs to be case insensitive but that need not be humanly readable".

Definition: RFC 4648 section 6 alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ234567, pad = to a multiple of 8 characters. Section 7 defines base32hex, an alphabet 0-9A-V that keeps the sort order of the bytes. Variants for humans:

VariantAlphabetRulesOrigin
RFC 4648 Base32A-Z 2-7upper-case, = padIETF; TOTP key URIs
base32hex0-9 A-Vsort-order preservingRFC 4648 section 7
Crockford0-9 A-Z without I L O Udecode accepts lower case, I/L as 1, O as 0, hyphens ignored, optional check symbol modulo 37Douglas Crockford
z-base-32ybndrfg8ejkmcpqxot1uwisza345h769lower case, shuffled so common characters are easyZooko Wilcox-O'Hearn

Crockford writes: "We exclude 4 of the 26 letters: I L O U", because I and L "can be confused with 1", O "can be confused with 0", and U gives "accidental obscenity". ULIDs use Crockford Base32; see ID generation.

text
bytes "hello" = 68 65 6c 6c 6f   (40 bits = exactly 8 groups of 5 bits)
RFC 4648 : NBSWY3DP
Crockford: D1JPRV3F
z-base-32: pb1sa5dx
TOTP secret JBSWY3DPEHPK3PXP -> 48 65 6c 6c 6f 21 de ad be ef   (10 bytes, 16 chars, no padding needed)

Real scenarios: the secret in an otpauth:// URI ("The secret parameter is an arbitrary key value encoded in Base32", per the Google Authenticator Key URI wiki) ; DNSSEC NSEC3 (RFC 5155 names the "Base 32 Encoding with Extended Hex Alphabet"); ULIDs (the spec says it "uses Crockford's base32"); recovery codes typed by users.

ProductBase32 API
Goencoding/base32 (StdEncoding, HexEncoding, NewEncoding(alphabet).WithPadding)
PHPnone built in; see the Base32 class in Solving or a library
JavaScriptnone native; libraries
Pythonbase64.b32encode, b32hexencode
PostgreSQLencode(x, 'base32hex') in the version 19 docs

Fix: for human-typed codes, group in fours and decode case-insensitively; for TOTP strip spaces and =. Code: alphabets.

Base58 Good to know ​

In plain words: a Base64-like alphabet with the look-alike characters removed so people can copy it from paper or a screen without mistakes, and with no + or / so double-click selects it as one word.

Common misunderstanding: "Base58 is a bit-slicing encoding like Base64." 58 is not a power of two, so it works like converting a huge number to another base: it needs big-integer division and is quadratic in the input length. It is for short values (keys, hashes, IDs), not megabytes.

Definition: the Bitcoin alphabet 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz; "0OIl are not used" in the Bitcoin source comment "Why base-58 instead of standard base-64 encoding? Don't want 0OIl characters that look the same in some fonts". Each leading zero byte is written as a leading 1. Base58Check appends a 4-byte double-SHA-256 checksum before encoding.

text
bytes  00 00 01 02 03 ff ee
b58    117bX9dP         (two leading zero bytes -> two leading '1')

Real scenarios: Bitcoin addresses and WIF keys; Bitcoin-style identifiers and short human-copied IDs in many systems.

ProductBase58
Gogithub.com/btcsuite/btcutil/base58 or the 40-line math/big version in alphabets
PHPlibraries (stephen-hill/base58php) or the class in Solving
VariantsBitcoin, Flickr (swapped case), Ripple (different order): same idea, different alphabet; never mix them

Base85 / Ascii85 Good to know ​

In plain words: four bytes become five characters from an 85-character alphabet: only 25% bigger instead of 33%.

Common misunderstanding: "Base85 is just Base64 but better." It uses characters (<, >, ', ", \, &) that hurt in HTML, JSON, shell and XML, so it fits file formats better than wire formats. Several incompatible alphabets exist.

Definition: Ascii85 (Adobe PostScript and PDF, originally Paul Rutter's btoa) treats four bytes as a 32-bit big-endian number, divides by 85 five times and adds 33 to each digit, giving ! through u; a group of four zero bytes can be written as z. (Secondary source: Wikipedia; the PostScript reference was not available to fetch.) Git writes binary patches with an 85-character table in base85.c: 0-9 A-Z a-z followed by !#$%&()*+-;<=>?@^_ and the backquote, braces, vertical bar and tilde (the same table Python's b85encode uses), with one length character at the start of each line. Z85 (ZeroMQ) and RFC 1924 (IPv6 addresses) are further variants.

text
$ git diff --binary          (real output)
GIT binary patch
literal 11
ScmZQzWODNKa}0|7{|^8Ro&&}J        <- 'S' encodes the line length, then Base85 of the (compressed) data

Real scenarios: PDF streams with /ASCII85Decode; git diff --binary and git format-patch --binary; PostScript; ZeroMQ (Z85).

ProductBase85
Goencoding/ascii85 (Adobe variant)
PHPnone built in (libraries)
Pythonbase64.a85encode, base64.b85encode (its alphabet, read from base64._b85alphabet, is 0-9A-Za-z then !#$%&()*+-;<=>?@^_{
Gitinternal base85.c: the 85-character table above, a length byte per line

Percent-encoding (URL encoding) Must-know ​

In plain words: a byte that is not allowed in a URL is written as % followed by two hex digits. A space is %20, an é (two bytes in UTF-8) is %C3%A9.

Common misunderstanding: "Percent-encode the whole URL before using it." Encoding is per component and per byte; encoding a finished URL escapes the : / ? # that were holding it together, and encoding twice turns %20 into %2520.

Definition (RFC 3986): pct-encoded = "%" HEXDIG HEXDIG; "unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"" never needs encoding. The reserved set is gen-delims (: / ? # [ ] @) and sub-delims (! $ & ' ( ) * + , ; =), which "provide a set of delimiting characters that are distinguishable from other data within a URI". RFC 3986 states "URI producers and normalizers should use uppercase hexadecimal digits for all percent-encodings", but %2f and %2F are equivalent. For text, first convert characters to bytes with UTF-8, then encode each byte.

text
"سلام دنیا"  UTF-8 bytes d8 b3 d9 84 d8 a7 d9 85 20 d8 af d9 86 db 8c d8 a7
path    : %D8%B3%D9%84%D8%A7%D9%85%20%D8%AF%D9%86%DB%8C%D8%A7     (51 chars, 3x)
query   : %D8%B3%D9%84%D8%A7%D9%85+%D8%AF%D9%86%DB%8C%D8%A7       (49 chars)

Real scenarios: search queries with Persian words; filenames with spaces in download links; redirect_uri parameters that contain a whole URL; OAuth state; tracking parameters.

FunctionEncodesSpace becomesLeaves alone
Go url.QueryEscapeeverything outside A-Za-z0-9 - _ . ~+unreserved only
Go url.PathEscapefor one path segment: escapes / ; , ? # and non-ASCII (measured)%20$ & + : = @ stay literal
PHP urlencodenon-alphanumeric except -_.+so ~ becomes %7E
PHP rawurlencodeRFC 3986%20-_.~
PHP http_build_querydefault PHP_QUERY_RFC1738+pass PHP_QUERY_RFC3986 for %20
JavaScript encodeURIComponentall but A-Za-z0-9 - _ . ! ~ * ' ( )%20for one component
JavaScript encodeURIwhole URL; keeps ; , / ? : @ & = + $ #%20for a full URL only
Python urllib.parse.quote / quote_pluspath-style / form-style%20 / +/ kept by default in quote

Fix: use the standard library for each component (urlbug); never write "?q=" + value.

+ versus %20, and the bug Must-know ​

In plain words: in a query string, many servers read a + as a space. So a Base64 value or an e-mail address like a+b@example.test loses its + on the way.

Common misunderstanding: "+ is a space in URLs." Only in application/x-www-form-urlencoded. In a path, + is a literal plus. RFC 3986 does not give + a meaning at all in a query (it is a sub-delimiter); the WHATWG URL Standard defines the form encoding that turns 0x20 into + and decodes + back: "Replace any 0x2B (+) in name and value with 0x20 (SP)." PHP's own manual says urlencode is "encoded the same way that the posted data from a WWW form is encoded".

text
client builds    GET /verify?token=++++//4=         (raw standard base64, not encoded)
server parses    token = "    //4="                  (each '+' -> space)
signature check  FAILS (the bytes changed)           -> 401 / "invalid token"
fix A            token=%2B%2B%2B%2B%2F%2F4%3D         (percent-encode on the client)
fix B            token=----__4                        (base64url: no '+' to lose)

Real scenarios: e-mail verification links; webhook signatures in query strings; Base64 tokens pasted into a browser address bar; Gmail-style +tag e-mail addresses in a query; a Kubernetes dashboard URL that includes a token.

Where+ means%20 means
URL patha plus signa space
URL query read as form data (PHP $_GET, Go Query(), Express req.query, Laravel $request->query())a spacea space
application/x-www-form-urlencoded bodya spacea space
multipart/form-data bodya plus sign (no percent decoding)not decoded as such
JavaScript encodeURIComponent outputnever produced; + becomes %2Bspace

Fix: encode every value you put in a query (url.Values.Encode, http_build_query, URLSearchParams), or avoid + and / by using base64url. Code: urlbug; lab: Lab 2.

Double encoding Important ​

In plain words: encoding a value that is already encoded, so % itself becomes %25, or decoding twice, so a %2520 turns into a space instead of %20.

Common misunderstanding: "Extra encoding is harmless; the server will decode it." It is harmful: RFC 3986 says "Implementations must not percent-encode or decode the same string more than once, as decoding an already decoded string might lead to misinterpreting a percent data octet as the beginning of a percent-encoding". It is also a classic security bypass: a filter decodes once and sees %2e%2e%2f; the application decodes again and walks ../.

text
raw        a b&c=d
once       a%20b%26c%3Dd
twice      a%2520b%2526c%253Dd       <- a link that works only after two decodes
server decodes once -> a%20b%26c%3Dd  <- user sees literal '%20' on the page

Real scenarios: a redirect URL put in redirect_uri that a framework encodes again; a CDN or proxy that normalises the path then the app decodes it; a message queue that stores an already-escaped payload; a link built by a helper and then escaped by e() again; path traversal bypasses (%252e%252e%252f).

LayerWho decodesRule
Reverse proxy / WAFmay normalise %2e, %2fdecode once at the edge, not again downstream
Framework routerdecodes the pathroute parameters are already decoded
Applicationdecodes querydo not call urldecode on a value the framework already decoded

Fix: encode exactly once, at the boundary where the value is put into a URL; decode exactly once, where it is taken out. Code: urlbug.

Path, query and fragment: three rule sets Important ​

In plain words: the same character is fine in one part of a URL and must be encoded in another.

Common misunderstanding: "One encoder works for every part." RFC 3986 defines a different allowed set per component (pchar for path segments, pchar / "/" / "?" for query and fragment), and the WHATWG URL Standard defines separate percent-encode sets (fragment, query, path, userinfo, component, form).

Definition: the generic syntax is scheme://userinfo@host:port/path?query#fragment. Encoding: the host uses IDNA/Punycode (or an IP literal); the path is encoded per segment (a / inside a segment must be %2F); the query is conventionally name=value pairs joined by &, each part form-encoded; the fragment is never sent to the server.

text
https://user:p%40ss@xn--mgbh0fb.xn--mgba3a4f16a:8443/%D9%85%D9%82%D8%A7%D9%84%D9%87/a%2Fb?q=a%2Bb+c&n=x%26y#%D8%A8%D8%AE%D8%B4-2
scheme    https
userinfo  user : p%40ss        '@' in the password is %40
host      xn--... (Punycode)
port      8443
path      %D9%85... / a%2Fb    segment "a/b" is one segment
query     q = "a+b c"   n = "x&y"
fragment  بخش-2 (browser only)
Same URL, different encoding per componenthttps://user:pw@مثال.ایران:8443/files/گزارش 1?q=a+b&n=x%26y#بخش-2schemeASCII letters onlyuserinfopercent-encode ':' '@'hostIDNA: xn--mgbh0fb...portdigitspath%20 for space, never +query+ means space (forms)fragmentnot sent to serverEncode each component separately, once, from raw text to bytes (UTF-8) to %XX. Never encode a whole URL.Reserved delimiters (: / ? # [ ] @ ! $ & ' ( ) * + , ; =) keep their meaning only in their own component.Unreserved (A-Z a-z 0-9 - . _ ~) never need encoding.

Real scenarios: S3 object keys with slashes and spaces; REST resources with e-mail addresses as IDs (/users/a%40b.test); search UIs with Persian queries; single-page apps whose fragment holds state; OAuth implicit-flow tokens in the fragment.

ComponentWhich characters must you encodeGoPHP
Path segment/ ? # %, space, non-ASCIIurl.PathEscaperawurlencode
Query value& = + # %, space, non-ASCIIurl.QueryEscape, url.Valueshttp_build_query, rawurlencode
Fragmentspace, non-ASCII, % (# only matters before it)u.Fragment, u.EscapedFragment()rawurlencode
Userinfo: @ / ? #url.UserPasswordrawurlencode per part
HostIDNA to xn--idna.Lookup.ToASCIIidn_to_ascii

Fix: build URLs with a URL type (net/url, League\Uri, Laravel route()/url()), not by string concatenation.

IRIs, Persian URLs and Punycode Important ​

In plain words: you can type https://مثال.ایران/مقاله/سلام in a browser; on the wire it becomes ASCII. The host uses Punycode (xn--mgbh0fb.xn--mgba3a4f16a), the path and query use percent-encoded UTF-8.

Common misunderstanding: "A URL can contain Persian letters." A URI cannot; an IRI can. RFC 3987 defines the IRI as "a sequence of characters from the Universal Character Set" with "a mapping from IRIs to URIs", and browsers do that mapping before sending. Server logs usually show the percent form. Also: Persian text mixes right-to-left letters with left-to-right ones, so the displayed order of a mixed URL may look scrambled while the stored order is fine.

Definition: Punycode (RFC 3492) is "a simple and efficient transfer encoding syntax designed for use with Internationalized Domain Names in Applications (IDNA)"; it "uniquely and reversibly transforms a Unicode string into an ASCII string". Each label that contains non-ASCII becomes xn-- plus the Punycode form. golang.org/x/net/idna documents the relation: it "implements IDNA2008 using the compatibility processing defined by UTS #46" (IDNA2008 is RFC 5890 to 5894). Persian text in paths and queries is UTF-8 first, then percent-encoded; Persian digits and ZWNJ (half-space, U+200C) are valid characters but frequent sources of mismatch ("Normalization" belongs to Bits, Bytes & Text Encoding).

text
مثال.ایران            -> xn--mgbh0fb.xn--mgba3a4f16a      (real output of x/net/idna)
bücher.example        -> xn--bcher-kva.example
IRI  https://مثال.ایران/مقاله/سلام?q=دنیا
URI  https://xn--mgbh0fb.xn--mgba3a4f16a/%D9%85%D9%82%D8%A7%D9%84%D9%87/%D8%B3%D9%84%D8%A7%D9%85?q=دنیا

(The Go standard url.URL leaves non-ASCII bytes in the query as-is in RawQuery; use url.Values.Encode() to produce %D8... for the wire.)

Real scenarios: a Persian news site with Persian slugs in paths; sitemap and canonical URLs that must agree on one form; a link shared in Telegram that appears decoded but pastes encoded; homograph phishing (look-alike Unicode domains) — browsers show Punycode for suspicious mixes; slugs generated by Str::slug that transliterate Persian to ASCII unless language is null.

ProductIDNA / IRI support
Gogolang.org/x/net/idna (Lookup, Registration, Display profiles); net/url does not convert hosts
PHPidn_to_ascii / idn_to_utf8 (ext-intl) with INTL_IDNA_VARIANT_UTS46
LaravelStr::slug($title, language: null) skips ASCII transliteration and keeps letters (\pL) such as Persian (framework source), Str::ascii; URL helpers percent-encode paths
Browsersshow Unicode hosts when the script mix looks safe, Punycode otherwise
curlconverts Unicode hosts to Punycode when built with IDN support; give paths already percent-encoded

Fix: store the canonical form you compare with (usually the encoded URI), convert at the edge, and never let a user-supplied Unicode host skip IDNA (Solving the classic problems). DNS side: DNS Resolution for Developers.

HTML entities and JSON escapes as "encodings" Important ​

In plain words: &lt; in HTML and \n or " in JSON are the same idea as %20: a way to write a character that is not allowed raw in that spot.

Common misunderstanding: "I escaped it once, so it is safe everywhere." Escaping is specific to the output context: HTML text, HTML attribute, JavaScript string, JSON string, URL, CSS. One output, one escaper.

Definition: HTML text needs &amp; and &lt; (and &quot; in attributes); characters can also be written &#1587; or &#x633;. JSON (RFC 8259) strings: "All Unicode characters may be placed within the quotation marks, except for the characters that MUST be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F)"; any character may be written \uXXXX.

text
HTML  <a href="/?q=1&x=2">Tom & "Jerry"</a>
   -> &lt;a href=&#34;/?q=1&amp;x=2&#34;&gt;Tom &amp; &#34;Jerry&#34;&lt;/a&gt;       (Go html.EscapeString)
JSON  {"s":"line1\nline2 \"q\" <tag> & سلام"}
   -> Go encoding/json default: <tag> &   (escapes <, >, & for HTML safety)

Real scenarios: XSS from unescaped user input in Blade's unescaped echo; JSON embedded in a script tag; a Persian name shown as &#1575;&#1581;...; JSON with 
 that broke old JavaScript parsers; double escaping that shows &amp;amp; on the page.

ProductHTML escapeJSON escape controls
Gohtml.EscapeString, html/template (contextual)encoding/json escapes <, >, &, U+2028/2029; Encoder.SetEscapeHTML(false)
PHP / Laravelhtmlspecialchars, Blade's double-brace echo (escapes automatically)JSON_UNESCAPED_UNICODE, JSON_UNESCAPED_SLASHES, JSON_HEX_TAG
JavaScripttextContent, templating librariesJSON.stringify (does not escape <)

Fix: use the contextual escaper of your template engine; never hand-concatenate HTML or JSON. Code: boundaries.

Data URIs Important ​

In plain words: a data: URL puts the whole file inside the URL: data:image/png;base64,iVBORw0KGgo.... No second request is needed.

Common misunderstanding: "Inline images are always faster." The bytes grow by a third, they cannot be cached separately from the page, they block rendering of the HTML that contains them, and they bypass any CDN. RFC 2397 itself says: "The 'data:' URL scheme is only useful for short values."

Definition (RFC 2397): dataurl := "data:" [ mediatype ] [ ";base64" ] "," data. Without ;base64 the data is written with percent-encoding; "If mediatype is omitted, it defaults to text/plain;charset=US-ASCII". MDN: "Browsers are not required to support any particular maximum length of data"; Chromium and Firefox accept up to 512 MB and Safari 2048 MB. Browsers treat data URLs as opaque origins.

text
data:text/plain;charset=UTF-8,%D8%B3%D9%84%D8%A7%D9%85%20%26%20hello         (percent form)
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQ...                 (base64 form, 86 B -> 138 chars)
CSP:  img-src 'self' data:        <- without 'data:' this inline image is BLOCKED

Real scenarios: tiny SVG icons and blurred image placeholders (LQIP); e-mail HTML with inline logos; a QR code returned as a data URL by an API; a downloaded report generated in JavaScript; a screenshot embedded in an issue.

AspectBehaviourProduct note
Sizebase64 form is +33%; prefix data:image/png;base64, adds 22 bytesmeasured: 86-byte PNG became 138 characters
Cachingnone separate from the documentuse files plus HTTP caching instead for big or reused images
CSPimg-src must allow data: explicitly; the CSP3 note says a non-HTTP(S) scheme "has to be ... explicitly specified (e.g. default-src * data:...)"; the CSP3 text also says developers "SHOULD NOT include either 'unsafe-inline', or data: as valid sources" for scriptsdata: in script-src enables XSS
E-mail clientssupport for data: images varies and some clients block them (not verified per client here)use cid: attachments or hosted images
OriginMDN: data URLs are treated as unique opaque originsdo not rely on same-origin access to inline content

Fix: inline only small, one-off assets (a few hundred bytes to a few KB); cap decoded size when you accept a data URI from users (datauri).

Quoted-printable and MIME encoded-words Good to know ​

In plain words: keep readable text as it is and only escape the troublesome bytes as =XX. Good for mostly-ASCII text with a few accents; bad for binary.

Common misunderstanding: "E-mail attachments are quoted-printable." Attachments are base64; quoted-printable is for text bodies. Non-ASCII headers (Subject, From names) use a different syntax, RFC 2047 encoded-words: =?utf-8?b?2LPZhNin2YU=?= (B = base64) or =?utf-8?q?=D8=B3...?= (Q = quoted-printable style).

Definition: RFC 2045 section 6.7: octets "MAY be represented as the US-ASCII characters which correspond to those octets" in the printable range, other bytes as = plus two hex digits, with soft line breaks (= at the end of a line) so "Encoded lines must not be longer than 76 characters". Content-Transfer-Encoding selects it (7bit, 8bit, binary, quoted-printable, base64).

text
Café = 5€   ->   Caf=C3=A9 =3D 5=E2=82=AC          (the literal "=" itself becomes =3D)
long line   ->   ...text...=<CRLF>...more text...    (soft break after 76 chars)
Subject: =?utf-8?b?2LPZhNin2YU=?=                    (RFC 2047, Persian "سلام")

Real scenarios: HTML e-mail bodies from mailers (Postfix, Symfony Mailer, PHPMailer); .eml files that show =3D where a = should be; raw MIME dumps in logs; a Subject that shows as =?UTF-8?B?... in a client that does not decode.

ProductAPI
Gomime/quotedprintable, mime.QEncoding / mime.BEncoding, mime.WordDecoder
PHPquoted_printable_encode / _decode, mb_encode_mimeheader, iconv_mime_encode
LaravelSymfony Mailer (underlying) picks base64 or quoted-printable per part

uuencode and other historical encodings Good to know ​

In plain words: the grandparent of Base64: three bytes into four characters in the range 32 to 95 (space to underscore), with a length character at the start of every line.

Common misunderstanding: "uuencode is obsolete, so nobody sees it." You still meet it in old Usenet archives, in begin 644 file blocks inside legacy mail, and in the macOS uuencode -m command (which actually writes Base64).

Definition: uuencode "originated in the Unix programs uuencode and uudecode written by Mary Ann Horton at the University of California, Berkeley in 1980" (Wikipedia, secondary). Its use of space and backquote and backslash made it fragile; Base64 chose letters, digits, + and /. Related: BinHex (classic Mac), yEnc (Usenet, 8-bit, about 1-2% overhead, never standardised), Base91, Z85.

text
$ printf hello | uuencode hello.txt      (real output, macOS)
begin 644 hello.txt
%:&5L;&\`
`
end

Fix: convert to Base64 (uudecode file | base64); do not generate new uuencode.

Base64 is not encryption Must-know ​

In plain words: Base64 is a way of spelling bytes. Anyone with a decoder (every language has one, and base64 -d is a single command) can read it.

Common misunderstanding: "It looks like random gibberish, so it is protected." Hiding in plain sight is obfuscation, not security; RFC 4648 warns this "has been known to cause security incidents when, e.g., a user reports details of a network protocol exchange ... and accidentally reveals the password because she is unaware that the base encoding does not protect the password." It also "adds no entropy to the plaintext, but it does increase the amount of data".

Definition: a secret needs a key. Encoding has no key. See Cryptography Fundamentals for AES-GCM and Password Hashing & Signed Tokens for passwords. The Kubernetes documentation says the same about Secrets: "Kubernetes Secrets are, by default, stored unencrypted in the API server's underlying data store (etcd)", and for the Docker auth field: "The auth value there is base64 encoded; it is obscured but not secret."

text
$ echo -n 'p@ss/w+rd' | base64
cEBzcy93K3Jk
$ echo cEBzcy93K3Jk | base64 -d
p@ss/w+rd                               <- one command, no key
Authorization: Basic bW9ydGV6YTpwQHNzOndvcmQ=   -> morteza:p@ss:word

Real scenarios: an API key "protected" by base64 in a mobile app (extractable in minutes); HTTP Basic over plain HTTP (credentials readable on the wire); Kubernetes Secrets committed to Git as YAML (the secret is in the repo); logging Authorization headers; JWT payloads that include personal data (they are readable by anyone holding the token).

ClaimReality
"Base64 hides it"reversible by anyone, no key
"JWT is encrypted"a normal JWT (JWS) is signed, not encrypted: base64url only; JWE is a different thing
"Kubernetes Secret is secure by default"stored unencrypted in etcd unless encryption at rest is enabled; RBAC controls access
"HTTP Basic is OK over HTTPS"yes over TLS; base64 adds nothing; credentials are visible to the server and any log that records the header

Fix: encrypt with a real cipher, hash passwords with a password hash, keep secrets out of Git and logs, and treat anything base64-encoded as plaintext.

Where each one shows up Important ​

In plain words: knowing which encoding a system uses lets you read it at a glance.

Common misunderstanding: "All these base64 strings are the same kind." They differ by alphabet and padding; the quick tell is the characters: - or _ means base64url, + or / means standard, = at the end means padded.

WhereEncodingDetail
JWT (JWS compact)base64url, no padding, three segments joined by .RFC 7515; header and payload are JSON, signature is raw bytes; eyJ is the tell-tale start of {"
Kubernetes Secret data:standard Base64 of the raw bytesstringData: takes plain text and the API server encodes it; Secrets are limited to 1 MiB
HTTP Basicstandard Base64 of user:password (RFC 7617)first colon splits, so user names cannot contain a colon
Docker config.json authBase64 of user:passwordobscured, not secret
E-mail attachmentsBase64 with 76-char lines (RFC 2045)Content-Transfer-Encoding: base64
HTML img srcdata URI (RFC 2397)CSP img-src data:
PEM files (certificates, keys)Base64 body, 64-char lines between -----BEGIN ...----- markerssee TLS in Practice
Git LFS pointer filetext file: version, oid sha256:<64 hex>, sizethe oid is hex of the content hash; pointers must be under 1024 bytes
Git binary patchGit's Base85git diff --binary
Protobuf JSON mappingbytes field becomes a Base64 string"JSON value will be the data encoded as a string using standard base64"; parsers accept both alphabets
Cookie valuesRFC 6265 allows + / =, forbids space, comma, semicolon, quote, backslash; at least 4096 bytes per cookieLaravel's session and encrypted cookies are Base64 of JSON
Laravel Encrypter payloadBase64 of a JSON object with base64 iv, value, mac, tagread in the framework source
TOTP secretBase32otpauth://totp/...?secret=JBSWY3DPEHPK3PXP
Laravel signed URLsignature= lower-case hex of HMAC-SHA256 over the URLnot base64
SSH, WireGuard keysBase6432-byte key = 44 characters with padding

Fix: when in doubt, decode with the matching variant and inspect; see the Lab.

Every boundary has its own escaping ruleClientbrowser, app,curl, Go, PHPServerdecodes eachlayer once, inthe right orderURL path/querypercent-encoding (UTF-8)Form bodyx-www-form-urlencoded: + for spaceJSON body\" \\ \n \uXXXX escapes; binary as base64HeadersBasic: base64; Cookie: base64url or hexHost namePunycode xn-- (IDNA)HTML responseentities: &lt; &amp; &quot;E-mail / MIMEbase64 or quoted-printable, 76 colsBug pattern: decode at the wrong boundary, twice, or not at all (a "+" that became a space, "%2520", &amp;amp;).

Per-language and per-tool behaviour ​

Go (encoding/base64, encoding/hex, encoding/base32, encoding/ascii85, net/url, mime/quotedprintable, html, golang.org/x/net/idna):

NeedAPINotes
Standard paddedbase64.StdEncodingdecoder ignores \r and \n only
Unpadded standardbase64.RawStdEncoding
URL-safe padded / unpaddedbase64.URLEncoding / base64.RawURLEncodingJWT uses RawURLEncoding
Custom alphabet / paddingbase64.NewEncoding(alphabet).WithPadding(rune); base64.NoPaddingalphabet must be 64 distinct bytes without \r \n
Reject non-zero trailing bitsenc.Strict()
Streamingbase64.NewEncoder(enc, w) (must Close), base64.NewDecoder(enc, r)
SizesEncodedLen, DecodedLen, AppendEncodeallocate buffers exactly
JSON[]byte fields become standard padded base64 stringsencoding/json
Hexhex.EncodeToString, hex.DecodeString, hex.Dump
Percenturl.QueryEscape, url.PathEscape, url.Values.Encode, url.ParseQuery

PHP (8.4) and Laravel 13:

NeedAPINotes
Base64base64_encode, base64_decode($s, strict: true)non-strict silently discards invalid characters
Base64urlrtrim(strtr(base64_encode($s), '+/', '-_'), '=')no built-in
Hexbin2hex, hex2bin
Percent (form)urlencode, urldecode, http_build_queryspace is +
Percent (RFC 3986)rawurlencode, rawurldecode, http_build_query($d, '', '&', PHP_QUERY_RFC3986)space is %20
Laravel string helpersStr::toBase64($s), Str::fromBase64($s, $strict = false)thin wrappers over base64_encode and base64_decode (framework source)
Laravel query buildingArr::query($array)calls http_build_query with PHP_QUERY_RFC3986
Laravel signed URLsURL::signedRoute, URL::temporarySignedRoute, $request->hasValidSignature(), signed middlewaresignature is hex hash_hmac('sha256', ...)
Laravel encryptionCrypt::encryptStringoutput is Base64 of JSON
Quoted-printablequoted_printable_encode
IDNidn_to_ascii, idn_to_utf8ext-intl

JavaScript (browser and Node):

NeedAPIPitfall
Base64 of a binary stringbtoa, atobbtoa('سلام') throws InvalidCharacterError because characters above 0xFF do not fit in a byte; MDN: "necessary to first convert the string to its constituent bytes in UTF-8, and then encode the bytes"
Base64 of bytesUint8Array.prototype.toBase64(), Uint8Array.fromBase64(); Node Buffer.from(x).toString('base64')Node 26 here reports Uint8Array.prototype.toBase64 as a function
PercentencodeURIComponent (component), encodeURI (whole URL), URLSearchParams (form rules, + for space)escape/unescape are deprecated; do not use
UTF-8 bytesnew TextEncoder().encode(str)

CLI tools:

ToolCommandBehaviour on this machine
base64 (macOS)printf hello | base64no wrapping; -b 76 wraps; echo hello adds \n and changes the output (aGVsbG8K)
base64 (GNU coreutils)base64 -w 0wraps at 76 by default: "The default is to wrap after 76 characters. Use the value 0 to disable line wrapping"
openssl base64openssl base64 -Awraps at 64 (measured); -A single line
xxdxxd -p, xxd -r -phex dump and reverse
curl--data-urlencode 'q=a+b'percent-encodes (lower-case hex: %2b)
kubectlkubectl get secret x -o jsonpath='{.data.password}' | base64 -ddecode a value
gitgit diff --binaryBase85 patches
PostgreSQLencode(x, 'hex' / 'base64' / 'escape'), decode(...)base64url and base32hex are in the 19 docs
sql
-- PostgreSQL: encode and decode bytea (documented: encode('123\000\001', 'base64') -> MTIzAAE=)
SELECT encode('\xd8b3d984d8a7d985'::bytea, 'hex')    AS hex,
       encode('\xd8b3d984d8a7d985'::bytea, 'base64') AS b64,
       convert_from(decode('2LPZhNin2YU=', 'base64'), 'UTF8') AS text_back;

Mechanics ​

Bit math and lengths ​

EncodingBits per charGroup (input to output)Encoded length for n bytes
Base1641 byte to 2 chars2n
Base3255 bytes to 8 chars8 * ceil(n / 5) padded
Base6463 bytes to 4 chars4 * ceil(n / 3) padded; ceil(4n / 3) unpadded
Base64 MIME6plus CRLF every 76 chars4 * ceil(n/3) + 2 * ceil(4*ceil(n/3) / 76)
Base85about 6.44 bytes to 5 chars5 * ceil(n / 4)
Base58about 5.86big-integer divisionabout 1.37n
Percentvariable1 byte to 3 chars when escapedn to 3n

Measured here: a 100 MiB file became 143,489,350 bytes with MIME wrapping (1.368x), exactly 4/3 * 78/76; 17 bytes of Persian text became 24 characters of padded Base64, 34 of hex, 49 to 51 of percent-encoding.

Line wrapping, quantums and pad bits ​

MIME wraps encoded output to at most 76 characters per line; RFC 2045 says "The 76 character limit does not count the trailing CRLF, but counts all other characters, including any equal signs." PEM uses 64. RFC 4648 allows implementations to choose and says decoders should reject characters outside the alphabet "unless the specification referring to this document explicitly states otherwise" (MIME does). The last 6-bit group may contain unused pad bits; RFC 4648 says they "MUST be set to zero" by encoders and decoders "MAY chose to reject an encoding if the pad bits have not been set to zero". This is why aGl= and aGk= both decode to hi in a lenient decoder but only aGk= is canonical (Go Strict() rejects the other). Two strings that decode to the same bytes break signature comparison, which is why you compare bytes, not encoded strings.

Performance, SIMD and streaming ​

Base64 is memory-bound on modern CPUs. Lemire and Muła's paper (arXiv 1910.05109) shows "encode and decode base64 data at nearly the speed of a memory copy (memcpy) on recent Intel processors" using AVX-512; PHP's own base64.c has AVX2, SSSE3 and AVX-512 paths selected at run time; the simdutf library provides base64 decoding with the WHATWG forgiving rules. Measured with go test -bench on this machine (Apple M5, Go 1.27, 1 MiB buffer): base64.Encode about 3.0 GB/s, Decode about 3.5 GB/s, EncodeToString 2.5 GB/s with two allocations (it allocates the output), hex encode 2.15 GB/s. The practical lessons: (1) allocate once with EncodedLen; (2) stream large files instead of building strings (measured: 100 MiB encoded with MIME wrapping and decoded again with a peak resident set of 9.7 MB, not 100+); (3) never base64 a large payload inside JSON when a binary or multipart channel exists, because the 33% is paid in bandwidth, CPU, memory and logging on both ends.

text
stream: file ──read 32 KiB──▶ base64.NewEncoder ──▶ line wrapper (76) ──▶ bufio ──▶ file
memory stays constant; Close() flushes the final 1-2 bytes and the "=" padding

Error messages you will see ​

Error textSourceMeaning
illegal base64 data at input byte NGo CorruptInputErrorwrong alphabet, wrong padding mode, or stray character (the offset is a hint, not always exact)
InvalidCharacterError: Invalid characterJavaScript atob / btoa (measured in Node)non-alphabet character, or Unicode passed to btoa
binascii.Error: Incorrect paddingPythonunpadded input to the padded decoder
base64_decode(): ... returns falsePHP strictcharacter outside the alphabet or wrong padding
URIError: URI malformedJavaScript decodeURIComponent('%zz') (measured)a % not followed by two hex digits, or invalid UTF-8
invalid URL escape "%zz"Go url.QueryUnescape (measured)% not followed by two hex digits
400 Bad Request with % in the pathweb servers and proxiesinvalid percent-escape, or an encoded / the server refuses (Apache has an AllowEncodedSlashes directive)
Invalid signature (Laravel 403)signed middlewareURL changed after signing: re-encoded, parameter reordered, or + mangled

Solving the classic problems ​

All Go programs below run with go run ./<dir> from docs/snippets/foundations/binary-to-text-encoding/go; PHP (8.4, Laravel 13) was reviewed, not executed, because PHP is not installed on this machine.

Problem 1: the same bytes through every encoding ​

SolutionHowAdvantageCost
One table of all formshex, base64, base32, ascii85, percent in one programshows size and look side by sidenone
go
// Command encodings shows the same bytes through every common
// binary-to-text encoding and prints the size cost of each.
package main

import (
	"encoding/ascii85"
	"encoding/base32"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"net/url"
)

func main() {
	text := "سلام دنیا" // "Hello world" in Persian, 9 characters
	raw := []byte(text)

	rows := []struct {
		name string
		out  string
	}{
		{"hex", hex.EncodeToString(raw)},
		{"base64 std (padded)", base64.StdEncoding.EncodeToString(raw)},
		{"base64 raw (no padding)", base64.RawStdEncoding.EncodeToString(raw)},
		{"base64url (padded)", base64.URLEncoding.EncodeToString(raw)},
		{"base64url raw", base64.RawURLEncoding.EncodeToString(raw)},
		{"base32 std", base32.StdEncoding.EncodeToString(raw)},
		{"base32 hex alphabet", base32.HexEncoding.EncodeToString(raw)},
		{"ascii85", ascii85Encode(raw)},
		{"percent (query)", url.QueryEscape(text)},
		{"percent (path segment)", url.PathEscape(text)},
	}

	fmt.Printf("input: %q  (%d runes, %d bytes in UTF-8)\n\n", text, len([]rune(text)), len(raw))
	fmt.Printf("%-26s %5s %7s  %s\n", "encoding", "len", "ratio", "output")
	for _, r := range rows {
		fmt.Printf("%-26s %5d %6.2fx  %s\n", r.name, len(r.out), float64(len(r.out))/float64(len(raw)), r.out)
	}
}

func ascii85Encode(b []byte) string {
	dst := make([]byte, ascii85.MaxEncodedLen(len(b)))
	n := ascii85.Encode(dst, b)
	return string(dst[:n])
}

Real output:

text
input: "سلام دنیا"  (9 runes, 17 bytes in UTF-8)

encoding                     len   ratio  output
hex                           34   2.00x  d8b3d984d8a7d98520d8afd986db8cd8a7
base64 std (padded)           24   1.41x  2LPZhNin2YUg2K/ZhtuM2Kc=
base64 raw (no padding)       23   1.35x  2LPZhNin2YUg2K/ZhtuM2Kc
base64url (padded)            24   1.41x  2LPZhNin2YUg2K_ZhtuM2Kc=
base64url raw                 23   1.35x  2LPZhNin2YUg2K_ZhtuM2Kc
base32 std                    32   1.88x  3CZ5TBGYU7MYKIGYV7MYNW4M3CTQ====
base32 hex alphabet           32   1.88x  R2PTJ16OKVCOA86OLVCODMSCR2JG====
ascii85                       22   1.29x  fX'7afVdDV+P<mNL>.[>VZ
percent (query)               49   2.88x  %D8%B3%D9%84%D8%A7%D9%85+%D8%AF%D9%86%DB%8C%D8%A7
percent (path segment)        51   3.00x  %D8%B3%D9%84%D8%A7%D9%85%20%D8%AF%D9%86%DB%8C%D8%A7

The PHP equivalent, plus base64url and Base32 helpers:

php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

/**
 * The same bytes through every common binary-to-text encoding in PHP.
 * PHP has native hex, base64, percent-encoding and (via convert.* filters)
 * quoted-printable; Base32 and Base58 are not in the standard library.
 */
final class Encodings
{
    /** RFC 4648 section 5: "-" and "_" instead of "+" and "/", padding removed. */
    public static function base64UrlEncode(string $bytes): string
    {
        return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
    }

    /** Returns false for anything that is not valid base64url (padding optional). */
    public static function base64UrlDecode(string $text): string|false
    {
        // Re-add the padding the encoder removed: length must be a multiple of 4.
        $padded = str_pad(strtr($text, '-_', '+/'), (int) (ceil(strlen($text) / 4) * 4), '=');

        return base64_decode($padded, strict: true);
    }

    /** @return array<string, string> label => encoded text, for one input. */
    public static function allForms(string $bytes): array
    {
        return [
            'hex'               => bin2hex($bytes),
            'base64'            => base64_encode($bytes),
            'base64 (no pad)'   => rtrim(base64_encode($bytes), '='),
            'base64url'         => self::base64UrlEncode($bytes),
            'base32'            => Base32::encode($bytes),
            'urlencode (form)'  => urlencode($bytes),     // space -> +, "~" -> %7E
            'rawurlencode'      => rawurlencode($bytes),  // RFC 3986: space -> %20
            'quoted-printable'  => quoted_printable_encode($bytes),
        ];
    }

    /** Size cost of each form relative to the input, as a ratio. */
    public static function overhead(string $bytes): array
    {
        $n = max(strlen($bytes), 1);

        return array_map(static fn (string $s): float => round(strlen($s) / $n, 2), self::allForms($bytes));
    }
}
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

use InvalidArgumentException;

/**
 * RFC 4648 Base32 (A-Z, 2-7), upper-case, optional padding. This is the
 * alphabet authenticator apps use for TOTP secrets (RFC 6238 only
 * specifies the key bytes; the otpauth:// URI uses Base32).
 */
final class Base32
{
    private const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';

    public static function encode(string $bytes, bool $pad = true): string
    {
        $bits = '';
        foreach (str_split($bytes) as $char) {
            $bits .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
        }

        $out = '';
        foreach (str_split($bits, 5) as $chunk) {
            // The last group is zero-extended to 5 bits (the "pad bits" of RFC 4648).
            $out .= self::ALPHABET[bindec(str_pad($chunk, 5, '0'))];
        }

        return $pad ? str_pad($out, (int) (ceil(strlen($out) / 8) * 8), '=') : $out;
    }

    public static function decode(string $text): string
    {
        // Case-insensitive on input, as authenticator apps print secrets in groups of four.
        $text = strtoupper(str_replace([' ', '-', '='], '', $text));

        $bits = '';
        foreach (str_split($text) as $char) {
            $value = strpos(self::ALPHABET, $char);
            if ($value === false) {
                throw new InvalidArgumentException("Invalid Base32 character: {$char}");
            }
            $bits .= str_pad(decbin($value), 5, '0', STR_PAD_LEFT);
        }

        $out = '';
        foreach (str_split($bits, 8) as $byte) {
            if (strlen($byte) === 8) { // drop the trailing pad bits
                $out .= chr((int) bindec($byte));
            }
        }

        return $out;
    }
}

Problem 2: the + that became a space (and double encoding) ​

SolutionHowAdvantageCost
Encode every query valueurl.Values.Encode, http_build_query, URLSearchParamscorrect for any valuemust remember at every call site
base64url instead of base64RawURLEncodingno + or / existsother side must accept base64url
Never decode twicedecode where the value leaves the URL, onceno %2520needs discipline across proxies
go
// Command urlbug reproduces the classic "+ became a space" bug and the
// double-encoding bug, then shows the correct way to build and read queries.
package main

import (
	"encoding/base64"
	"fmt"
	"net/url"
)

func main() {
	token := base64.StdEncoding.EncodeToString([]byte{0xfb, 0xef, 0xbe, 0xff, 0xfe}) // contains + and /
	fmt.Println("token:", token)

	// BUG: concatenating the raw value into the query string.
	broken := "https://api.example.test/verify?token=" + token
	u, _ := url.Parse(broken)
	got := u.Query().Get("token")
	fmt.Printf("broken URL : %s\n", broken)
	fmt.Printf("server sees: %q  (same as sent? %v)\n\n", got, got == token)

	// FIX 1: let net/url encode the value.
	v := url.Values{}
	v.Set("token", token)
	fixed := "https://api.example.test/verify?" + v.Encode()
	u2, _ := url.Parse(fixed)
	got2 := u2.Query().Get("token")
	fmt.Printf("fixed URL  : %s\n", fixed)
	fmt.Printf("server sees: %q  (same as sent? %v)\n\n", got2, got2 == token)

	// FIX 2: do not put '+' and '/' on the wire at all.
	urlSafe := base64.RawURLEncoding.EncodeToString([]byte{0xfb, 0xef, 0xbe, 0xff, 0xfe})
	fmt.Println("base64url  :", urlSafe)

	// Double encoding: encoding an already-encoded value.
	once := url.QueryEscape("a b&c=d")
	twice := url.QueryEscape(once)
	decodedOnce, _ := url.QueryUnescape(twice)
	fmt.Printf("\nonce  : %s\ntwice : %s\ndecode(twice) once -> %s  (still encoded)\n", once, twice, decodedOnce)

	// '+' versus %20: the same string, two different rules.
	fmt.Println("\nQueryEscape(\"a b+c\") =", url.QueryEscape("a b+c"))
	fmt.Println("PathEscape (\"a b+c\") =", url.PathEscape("a b+c"))
	pu, _ := url.Parse("https://example.test/files/a+b%20c?q=a+b%20c")
	fmt.Printf("path decoded: %q   query decoded: %q\n", pu.Path, pu.Query().Get("q"))
}

Real output:

text
token: ++++//4=
broken URL : https://api.example.test/verify?token=++++//4=
server sees: "    //4="  (same as sent? false)

fixed URL  : https://api.example.test/verify?token=%2B%2B%2B%2B%2F%2F4%3D
server sees: "++++//4="  (same as sent? true)

base64url  : ----__4

once  : a+b%26c%3Dd
twice : a%2Bb%2526c%253Dd
decode(twice) once -> a+b%26c%3Dd  (still encoded)

QueryEscape("a b+c") = a+b%2Bc
PathEscape ("a b+c") = a%20b+c
path decoded: "/files/a+b c"   query decoded: "a b c"
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

/**
 * Reproduces and fixes the "+ became a space" bug. PHP decodes a query
 * string with form rules (plus means space), so a raw standard-base64
 * value loses every "+".
 */
final class UrlBug
{
    public static function demo(): void
    {
        $token = base64_encode("\xfb\xef\xbe\xff\xfe"); // "++++//4="

        // BUG: concatenating the value into the query string.
        $broken = 'https://api.example.test/verify?token=' . $token;
        parse_str((string) parse_url($broken, PHP_URL_QUERY), $query);
        var_dump($query['token'] === $token); // bool(false): "    //4="

        // FIX 1: let http_build_query encode it (RFC 1738 by default: space -> +, "+" -> %2B).
        $fixed = 'https://api.example.test/verify?' . http_build_query(['token' => $token]);
        parse_str((string) parse_url($fixed, PHP_URL_QUERY), $query);
        var_dump($query['token'] === $token); // bool(true)

        // FIX 2: RFC 3986 encoding for query values that are not form posts.
        echo http_build_query(['q' => 'a b+c'], '', '&', PHP_QUERY_RFC3986), PHP_EOL; // q=a%20b%2Bc

        // FIX 3: do not put "+" and "/" on the wire at all.
        echo Encodings::base64UrlEncode("\xfb\xef\xbe\xff\xfe"), PHP_EOL; // ----__4

        // Double encoding: encode once at the boundary, never twice.
        $once = rawurlencode('a b&c=d');   // a%20b%26c%3Dd
        $twice = rawurlencode($once);      // a%2520b%2526c%253Dd
        echo rawurldecode($twice), PHP_EOL; // a%20b%26c%3Dd  (still encoded)

        // Path segment versus query value: "+" is only a space in the query.
        echo urldecode('a+b%20c'), '|', rawurldecode('a+b%20c'), PHP_EOL; // "a b c" | "a+b c"
    }
}

Problem 3: padding stripped, wrong alphabet, sloppy bits ​

go
// Command padding shows how Go's base64 decoders treat padding,
// whitespace, the two alphabets and trailing bits.
package main

import (
	"encoding/base64"
	"fmt"
)

func try(name string, enc *base64.Encoding, in string) {
	out, err := enc.DecodeString(in)
	if err != nil {
		fmt.Printf("%-34s %-22q -> error: %v\n", name, in, err)
		return
	}
	fmt.Printf("%-34s %-22q -> %q\n", name, in, out)
}

func main() {
	// "hi!" is 3 bytes: no padding needed. "hi" is 2 bytes: one '='.
	try("Std, padded input", base64.StdEncoding, "aGkh")
	try("Std, 2 bytes, padded", base64.StdEncoding, "aGk=")
	try("Std, 2 bytes, padding stripped", base64.StdEncoding, "aGk")
	try("RawStd, padding present", base64.RawStdEncoding, "aGk=")
	try("RawStd, padding stripped", base64.RawStdEncoding, "aGk")

	// Alphabet mix-ups: '+' and '/' vs '-' and '_'.
	try("Std decodes url-safe input", base64.StdEncoding, "-_-_")
	try("URL decodes std input", base64.URLEncoding, "+/+/")

	// Go silently drops CR and LF but nothing else.
	try("Std, MIME line break inside", base64.StdEncoding, "aGVs\r\nbG8h")
	try("Std, space inside", base64.StdEncoding, "aGVs bG8h")

	// Non-zero trailing bits: "aGl=" decodes like "aGk=" unless Strict.
	try("Std, sloppy trailing bits", base64.StdEncoding, "aGl=")
	try("Std.Strict(), sloppy trailing bits", base64.StdEncoding.Strict(), "aGl=")

	// A percent-encoded '=' from a query string is not base64.
	try("Std, still percent-encoded", base64.StdEncoding, "aGk%3D")
}

Real output (note the first error offsets are Go's report, not a promise):

text
Std, padded input                  "aGkh"                 -> "hi!"
Std, 2 bytes, padded               "aGk="                 -> "hi"
Std, 2 bytes, padding stripped     "aGk"                  -> error: illegal base64 data at input byte 0
RawStd, padding present            "aGk="                 -> error: illegal base64 data at input byte 3
RawStd, padding stripped           "aGk"                  -> "hi"
Std decodes url-safe input         "-_-_"                 -> error: illegal base64 data at input byte 0
URL decodes std input              "+/+/"                 -> error: illegal base64 data at input byte 0
Std, MIME line break inside        "aGVs\r\nbG8h"         -> "hello!"
Std, space inside                  "aGVs bG8h"            -> error: illegal base64 data at input byte 4
Std, sloppy trailing bits          "aGl="                 -> "hi"
Std.Strict(), sloppy trailing bits "aGl="                 -> error: illegal base64 data at input byte 3
Std, still percent-encoded         "aGk%3D"               -> error: illegal base64 data at input byte 3

PHP: use base64UrlDecode in Encodings.php (re-pads, then base64_decode(..., strict: true)).

Problem 4: decoding attacker-controlled base64 and length limits ​

SolutionHowAdvantageCost
Cap before decodereject len(s) > max; http.MaxBytesReader; Laravel max:no big allocationchoose a sensible limit
Decode strictlyGo Strict(); PHP strict: truerejects noise and ambiguitybreaks lenient producers
Cap after decodeDecodedLen checkcatches expansion trickstiny
Verify content, not labelcheck PNG/JPEG magic bytes, re-encode imagesstops disguised payloadsmore code
go
// Command safedecode shows how to accept base64 from an untrusted client:
// cap the encoded length before decoding, decode strictly, cap the decoded
// size, and never trust what the bytes claim to be.
package main

import (
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
)

const (
	maxEncoded = 4 * 1024 // 4 KiB of base64 is plenty for a token or avatar hash
)

var ErrTooLarge = errors.New("payload too large")

// DecodeUntrusted decodes standard padded base64 with a hard size limit.
func DecodeUntrusted(s string) ([]byte, error) {
	if len(s) > maxEncoded {
		return nil, ErrTooLarge // reject before allocating anything
	}
	enc := base64.StdEncoding.Strict() // reject non-zero trailing bits
	// Refuse whitespace and line breaks: the lenient decoder would skip CR/LF.
	if strings.ContainsAny(s, "\r\n \t") {
		return nil, errors.New("whitespace not allowed")
	}
	out := make([]byte, enc.DecodedLen(len(s)))
	n, err := enc.Decode(out, []byte(s))
	if err != nil {
		return nil, err
	}
	return out[:n], nil
}

// handler reads a JSON-free body that is itself base64, with a body cap.
func handler(w http.ResponseWriter, r *http.Request) {
	r.Body = http.MaxBytesReader(w, r.Body, maxEncoded+1) // cap the read, not just the decode
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "too large", http.StatusRequestEntityTooLarge)
		return
	}
	raw, err := DecodeUntrusted(string(body))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	fmt.Fprintf(w, "ok %d bytes", len(raw))
}

func main() {
	srv := httptest.NewServer(http.HandlerFunc(handler))
	defer srv.Close()

	cases := []struct{ name, body string }{
		{"valid", base64.StdEncoding.EncodeToString([]byte("hello"))},
		{"newline injected", "aGVs\nbG8="},
		{"sloppy trailing bits", "aGl="},
		{"oversize", strings.Repeat("A", 10_000)},
	}
	for _, c := range cases {
		resp, err := http.Post(srv.URL, "text/plain", strings.NewReader(c.body))
		if err != nil {
			panic(err)
		}
		b, _ := io.ReadAll(resp.Body)
		resp.Body.Close()
		fmt.Printf("%-22s -> %d %s\n", c.name, resp.StatusCode, strings.TrimSpace(string(b)))
	}
}

Real output:

text
valid                  -> 200 ok 5 bytes
newline injected       -> 400 whitespace not allowed
sloppy trailing bits   -> 400 illegal base64 data at input byte 3
oversize               -> 413 too large
php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * Accepting base64 from an untrusted client: cap the encoded length first,
 * decode strictly, cap the decoded size, then verify what the bytes are.
 */
final class SafeBase64Controller extends Controller
{
    private const MAX_ENCODED = 4096;

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            // max applies to the string length, before any decoding happens.
            // The regex ends in \z, not $, because "$" would accept a trailing newline.
            'avatar' => ['required', 'string', 'max:' . self::MAX_ENCODED, 'regex:/^[A-Za-z0-9+\/]+={0,2}\z/'],
        ]);

        // Str::fromBase64 is base64_decode($value, $strict); pass true to reject stray characters.
        $bytes = Str::fromBase64($request->string('avatar')->toString(), strict: true);
        abort_if($bytes === false, 422, 'avatar is not valid base64');

        // Do not trust the label: inspect the bytes (PNG signature here).
        abort_unless(str_starts_with($bytes, "\x89PNG\r\n\x1a\n"), 422, 'avatar must be a PNG');

        return response()->json(['bytes' => strlen($bytes)]);
    }
}

Problem 5: a large file in constant memory ​

go
// Command stream base64-encodes and decodes a large file in constant
// memory, optionally wrapping lines at 76 characters as MIME requires.
package main

import (
	"bufio"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"io"
	"os"
	"path/filepath"
)

// lineWrapper inserts CRLF after every n bytes written (RFC 2045: n = 76).
type lineWrapper struct {
	w   io.Writer
	n   int
	col int
}

func (l *lineWrapper) Write(p []byte) (int, error) {
	written := 0
	for len(p) > 0 {
		room := l.n - l.col
		chunk := p
		if len(chunk) > room {
			chunk = chunk[:room]
		}
		if _, err := l.w.Write(chunk); err != nil {
			return written, err
		}
		written += len(chunk)
		l.col += len(chunk)
		p = p[len(chunk):]
		if l.col == l.n {
			if _, err := l.w.Write([]byte("\r\n")); err != nil {
				return written, err
			}
			l.col = 0
		}
	}
	return written, nil
}

func encodeFile(src, dst string, mime bool) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()

	bw := bufio.NewWriterSize(out, 64*1024)
	var sink io.Writer = bw
	if mime {
		sink = &lineWrapper{w: bw, n: 76}
	}
	enc := base64.NewEncoder(base64.StdEncoding, sink)
	if _, err := io.Copy(enc, in); err != nil { // 32 KiB at a time
		return err
	}
	if err := enc.Close(); err != nil { // flushes the final partial group and padding
		return err
	}
	return bw.Flush()
}

func decodeFile(src, dst string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()
	out, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer out.Close()
	// The decoder skips CR and LF, so MIME-wrapped input works unchanged.
	_, err = io.Copy(out, base64.NewDecoder(base64.StdEncoding, bufio.NewReaderSize(in, 64*1024)))
	return err
}

func sum(path string) string {
	f, _ := os.Open(path)
	defer f.Close()
	h := sha256.New()
	_, _ = io.Copy(h, f)
	return fmt.Sprintf("%x", h.Sum(nil))[:16]
}

func main() {
	dir, _ := os.MkdirTemp("", "b64")
	defer os.RemoveAll(dir)
	src := filepath.Join(dir, "big.bin")

	// 100 MiB of deterministic bytes, written without holding them in memory.
	f, _ := os.Create(src)
	block := make([]byte, 1<<20)
	for i := range block {
		block[i] = byte(i * 31)
	}
	for i := 0; i < 100; i++ {
		_, _ = f.Write(block)
	}
	f.Close()

	enc, back := filepath.Join(dir, "big.b64"), filepath.Join(dir, "big.out")
	if err := encodeFile(src, enc, true); err != nil {
		panic(err)
	}
	if err := decodeFile(enc, back); err != nil {
		panic(err)
	}
	a, _ := os.Stat(src)
	b, _ := os.Stat(enc)
	fmt.Printf("source %d bytes, base64+MIME %d bytes (%.3fx)\n", a.Size(), b.Size(), float64(b.Size())/float64(a.Size()))
	fmt.Printf("sha256 before %s, after %s\n", sum(src), sum(back))
}

Real output (100 MiB, MIME-wrapped, round trip verified):

text
source 104857600 bytes, base64+MIME 143489350 bytes (1.368x)
sha256 before 7264223ed5715d75, after 7264223ed5715d75
maximum resident set size: 9748480 bytes   (from /usr/bin/time -l on the built binary)
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

use RuntimeException;

/**
 * Base64 a large file in constant memory with PHP stream filters.
 * convert.base64-encode accepts line-length and line-break-chars, which
 * gives MIME-style wrapping at 76 characters.
 */
final class StreamBase64
{
    public static function encodeFile(string $source, string $target, bool $mime = true): void
    {
        $in = fopen($source, 'rb');
        $out = fopen($target, 'wb');
        if ($in === false || $out === false) {
            throw new RuntimeException('Cannot open files');
        }

        $params = $mime ? ['line-length' => 76, 'line-break-chars' => "\r\n"] : [];
        $filter = stream_filter_append($out, 'convert.base64-encode', STREAM_FILTER_WRITE, $params);

        stream_copy_to_stream($in, $out); // copies in 8 KiB chunks; memory stays flat

        stream_filter_remove($filter); // flushes the final partial group and the "=" padding
        fclose($in);
        fclose($out);
    }

    public static function decodeFile(string $source, string $target): void
    {
        $in = fopen($source, 'rb');
        $out = fopen($target, 'wb');
        stream_filter_append($in, 'convert.base64-decode', STREAM_FILTER_READ);
        stream_copy_to_stream($in, $out);
        fclose($in);
        fclose($out);
    }
}

Problem 6: data URIs, built and parsed safely ​

go
// Command datauri builds an RFC 2397 data URI from a generated PNG and
// parses one back, with a size cap so a hostile value cannot exhaust memory.
package main

import (
	"bytes"
	"encoding/base64"
	"errors"
	"fmt"
	"image"
	"image/color"
	"image/png"
	"net/url"
	"strings"
)

const maxDecoded = 64 * 1024 // refuse inline payloads above 64 KiB

func buildPNG() []byte {
	img := image.NewRGBA(image.Rect(0, 0, 16, 16))
	for y := 0; y < 16; y++ {
		for x := 0; x < 16; x++ {
			img.Set(x, y, color.RGBA{R: uint8(x * 16), G: uint8(y * 16), B: 128, A: 255})
		}
	}
	var buf bytes.Buffer
	if err := png.Encode(&buf, img); err != nil {
		panic(err)
	}
	return buf.Bytes()
}

// Encode returns data:<mediatype>;base64,<payload>.
func Encode(mediaType string, payload []byte) string {
	return "data:" + mediaType + ";base64," + base64.StdEncoding.EncodeToString(payload)
}

// EncodeText returns a non-base64 data URI where the payload is percent-encoded.
func EncodeText(mediaType, text string) string {
	return "data:" + mediaType + "," + url.PathEscape(text)
}

// Decode parses data:[<mediatype>][;base64],<data> and enforces a size cap.
func Decode(uri string) (mediaType string, payload []byte, err error) {
	rest, ok := strings.CutPrefix(uri, "data:")
	if !ok {
		return "", nil, errors.New("not a data URI")
	}
	meta, data, ok := strings.Cut(rest, ",")
	if !ok {
		return "", nil, errors.New("missing comma")
	}
	isB64 := false
	if m, found := strings.CutSuffix(meta, ";base64"); found {
		meta, isB64 = m, true
	}
	if meta == "" {
		meta = "text/plain;charset=US-ASCII" // RFC 2397 default
	}
	if isB64 {
		if base64.StdEncoding.DecodedLen(len(data)) > maxDecoded {
			return "", nil, errors.New("data URI too large")
		}
		payload, err = base64.StdEncoding.DecodeString(data)
	} else {
		if len(data) > maxDecoded {
			return "", nil, errors.New("data URI too large")
		}
		var s string
		s, err = url.PathUnescape(data)
		payload = []byte(s)
	}
	return meta, payload, err
}

func main() {
	pngBytes := buildPNG()
	uri := Encode("image/png", pngBytes)
	fmt.Printf("png bytes: %d, data URI length: %d (%.2fx)\n", len(pngBytes), len(uri), float64(len(uri))/float64(len(pngBytes)))
	fmt.Println(uri[:60] + "...")
	fmt.Printf("<img src=%q>\n", uri[:40]+"...")

	mt, back, err := Decode(uri)
	fmt.Printf("decoded: type=%s bytes=%d same=%v err=%v\n", mt, len(back), bytes.Equal(back, pngBytes), err)

	txt := EncodeText("text/plain;charset=UTF-8", "سلام & hello")
	fmt.Println(txt)
	mt, back, err = Decode(txt)
	fmt.Printf("decoded: type=%s text=%q err=%v\n", mt, back, err)

	_, _, err = Decode("data:application/octet-stream;base64," + strings.Repeat("A", 200_000))
	fmt.Println("oversize:", err)
}

Real output:

text
png bytes: 86, data URI length: 138 (1.60x)
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAA...
<img src="data:image/png;base64,iVBORw0KGgoAAAANSU...">
decoded: type=image/png bytes=86 same=true err=<nil>
data:text/plain;charset=UTF-8,%D8%B3%D9%84%D8%A7%D9%85%20&%20hello
decoded: type=text/plain;charset=UTF-8 text="سلام & hello" err=<nil>
oversize: data URI too large
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

use InvalidArgumentException;

/** RFC 2397 data URIs with a size cap. */
final class DataUri
{
    private const MAX_DECODED = 64 * 1024;

    public static function fromFile(string $path): string
    {
        $mime = mime_content_type($path) ?: 'application/octet-stream';

        return 'data:' . $mime . ';base64,' . base64_encode((string) file_get_contents($path));
    }

    /** @return array{mediaType: string, bytes: string} */
    public static function parse(string $uri): array
    {
        if (! str_starts_with($uri, 'data:') || ! str_contains($uri, ',')) {
            throw new InvalidArgumentException('Not a data URI');
        }

        [$meta, $data] = explode(',', substr($uri, 5), 2);
        $isBase64 = str_ends_with($meta, ';base64');
        $mediaType = $isBase64 ? substr($meta, 0, -7) : $meta;
        $mediaType = $mediaType === '' ? 'text/plain;charset=US-ASCII' : $mediaType; // RFC 2397 default

        // Check the size before decoding anything.
        if (strlen($data) > self::MAX_DECODED * 4 / 3 + 4) {
            throw new InvalidArgumentException('Data URI too large');
        }

        $bytes = $isBase64 ? base64_decode($data, strict: true) : rawurldecode($data);
        if ($bytes === false || strlen($bytes) > self::MAX_DECODED) {
            throw new InvalidArgumentException('Invalid or oversized data URI');
        }

        return ['mediaType' => $mediaType, 'bytes' => $bytes];
    }
}

Problem 7: Crockford, z-base-32, Base58, TOTP secrets ​

go
// Command alphabets implements the "other" bases from first principles:
// Crockford Base32 with its check symbol, z-base-32, Base58 (Bitcoin
// alphabet) and Git's Base85, and decodes a TOTP-style Base32 secret.
package main

import (
	"encoding/base32"
	"fmt"
	"math/big"
	"strings"
)

// Crockford Base32: no I, L, O, U; encode uppercase, decode case-insensitive.
const crockford = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"

var crockfordEnc = base32.NewEncoding(crockford).WithPadding(base32.NoPadding)

// normalizeCrockford applies the decoding rules: ignore hyphens, fold case,
// map I and L to 1 and O to 0.
func normalizeCrockford(s string) string {
	s = strings.ToUpper(strings.ReplaceAll(s, "-", ""))
	r := strings.NewReplacer("I", "1", "L", "1", "O", "0")
	return r.Replace(s)
}

// zbase32 is Zooko's human-oriented alphabet.
var zbase32Enc = base32.NewEncoding("ybndrfg8ejkmcpqxot1uwisza345h769").WithPadding(base32.NoPadding)

const base58Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

// Base58Encode converts bytes to Base58; each leading zero byte becomes '1'.
func Base58Encode(in []byte) string {
	n := new(big.Int).SetBytes(in)
	base := big.NewInt(58)
	mod := new(big.Int)
	var out []byte
	for n.Sign() > 0 {
		n.DivMod(n, base, mod)
		out = append(out, base58Alphabet[mod.Int64()])
	}
	for _, b := range in {
		if b != 0 {
			break
		}
		out = append(out, base58Alphabet[0])
	}
	for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
		out[i], out[j] = out[j], out[i]
	}
	return string(out)
}

// Base58Decode reverses Base58Encode.
func Base58Decode(s string) ([]byte, error) {
	n := new(big.Int)
	base := big.NewInt(58)
	for _, c := range s {
		i := strings.IndexRune(base58Alphabet, c)
		if i < 0 {
			return nil, fmt.Errorf("invalid base58 character %q", c)
		}
		n.Mul(n, base)
		n.Add(n, big.NewInt(int64(i)))
	}
	out := n.Bytes()
	zeros := 0
	for zeros < len(s) && s[zeros] == base58Alphabet[0] {
		zeros++
	}
	return append(make([]byte, zeros), out...), nil
}

func main() {
	data := []byte{0x00, 0x00, 0x01, 0x02, 0x03, 0xff, 0xee}
	fmt.Println("bytes          :", fmt.Sprintf("% x", data))
	fmt.Println("base58         :", Base58Encode(data))
	back, _ := Base58Decode(Base58Encode(data))
	fmt.Printf("round trip     : % x\n", back)

	// Crockford
	c := crockfordEnc.EncodeToString([]byte("hello"))
	fmt.Println("crockford      :", c)
	typed := "d1jprv3f" // lower case, '1' typed as 'l' still decodes
	typed = strings.Replace(typed, "1", "l", 1)
	dec, _ := crockfordEnc.DecodeString(normalizeCrockford(typed))
	fmt.Printf("crockford typed %q -> %q\n", typed, dec)

	// z-base-32
	fmt.Println("z-base-32      :", zbase32Enc.EncodeToString([]byte("hello")))

	// TOTP secrets are RFC 4648 base32: upper-case, usually unpadded in apps.
	secret := "JBSWY3DPEHPK3PXP"
	key, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(strings.ToUpper(strings.ReplaceAll(secret, " ", "")))
	fmt.Printf("TOTP secret %s -> %d bytes % x err=%v\n", secret, len(key), key, err)
}

Real output:

text
bytes          : 00 00 01 02 03 ff ee
base58         : 117bX9dP
round trip     : 00 00 01 02 03 ff ee
crockford      : D1JPRV3F
crockford typed "dljprv3f" -> "hello"
z-base-32      : pb1sa5dx
TOTP secret JBSWY3DPEHPK3PXP -> 10 bytes 48 65 6c 6c 6f 21 de ad be ef err=<nil>
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

use InvalidArgumentException;

/**
 * Base58 with the Bitcoin alphabet: no 0, O, I, l; no "+" or "/".
 * Leading zero bytes become leading "1" characters.
 * Plain integer arithmetic on a digit array, so no gmp/bcmath is needed.
 */
final class Base58
{
    private const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';

    public static function encode(string $bytes): string
    {
        $digits = [0]; // base-58 digits, least significant first
        foreach (str_split($bytes) as $char) {
            $carry = ord($char);
            foreach ($digits as $i => $d) {
                $carry += $d << 8;
                $digits[$i] = $carry % 58;
                $carry = intdiv($carry, 58);
            }
            while ($carry > 0) {
                $digits[] = $carry % 58;
                $carry = intdiv($carry, 58);
            }
        }

        $out = '';
        foreach ($digits as $d) {
            $out = self::ALPHABET[$d] . $out;
        }
        $out = ltrim($out, '1'); // the all-zero value has no digits of its own
        $leadingZeros = strlen($bytes) - strlen(ltrim($bytes, "\0"));

        return str_repeat('1', $leadingZeros) . $out;
    }

    public static function decode(string $text): string
    {
        $bytes = [0]; // base-256 digits, least significant first
        foreach (str_split($text) as $char) {
            $carry = strpos(self::ALPHABET, $char);
            if ($carry === false) {
                throw new InvalidArgumentException("Invalid Base58 character: {$char}");
            }
            foreach ($bytes as $i => $b) {
                $carry += $b * 58;
                $bytes[$i] = $carry & 0xFF;
                $carry >>= 8;
            }
            while ($carry > 0) {
                $bytes[] = $carry & 0xFF;
                $carry >>= 8;
            }
        }

        $out = '';
        foreach ($bytes as $b) {
            $out = chr($b) . $out;
        }
        $out = ltrim($out, "\0");
        $leadingOnes = strlen($text) - strlen(ltrim($text, '1'));

        return str_repeat("\0", $leadingOnes) . $out;
    }
}

Problem 8: Persian domains and URLs (IDNA) ​

go
// Command idna converts internationalized domain names between Unicode and
// the ASCII "xn--" form (Punycode, RFC 3492; IDNA 2008 via x/net/idna) and
// shows the two spellings of a Persian URL: IRI versus URI.
package main

import (
	"fmt"
	"net/url"

	"golang.org/x/net/idna"
)

func main() {
	for _, host := range []string{"مثال.ایران", "bücher.example", "例え.jp"} {
		ascii, err := idna.Lookup.ToASCII(host)
		back, _ := idna.Lookup.ToUnicode(ascii)
		fmt.Printf("%-18s -> %-28s -> %s (err=%v)\n", host, ascii, back, err)
	}

	// An IRI (RFC 3987) with a Persian path and query.
	iri := "https://مثال.ایران/مقاله/سلام?q=دنیا"
	u, err := url.Parse(iri)
	if err != nil {
		panic(err)
	}
	host, _ := idna.Lookup.ToASCII(u.Hostname())
	u.Host = host
	fmt.Println("IRI :", iri)
	fmt.Println("URI :", u.String())
	fmt.Println("path:", u.EscapedPath(), " raw query:", u.RawQuery)
}

Real output:

text
مثال.ایران         -> xn--mgbh0fb.xn--mgba3a4f16a  -> مثال.ایران (err=<nil>)
bücher.example     -> xn--bcher-kva.example        -> bücher.example (err=<nil>)
例え.jp              -> xn--r8jz45g.jp               -> 例え.jp (err=<nil>)
IRI : https://مثال.ایران/مقاله/سلام?q=دنیا
URI : https://xn--mgbh0fb.xn--mgba3a4f16a/%D9%85%D9%82%D8%A7%D9%84%D9%87/%D8%B3%D9%84%D8%A7%D9%85?q=دنیا
path: /%D9%85%D9%82%D8%A7%D9%84%D9%87/%D8%B3%D9%84%D8%A7%D9%85  raw query: q=دنیا

Problem 9: HTML, JSON, quoted-printable, MIME headers ​

go
// Command boundaries shows the "other encodings" that guard other
// boundaries: HTML entities, JSON string escapes, quoted-printable and
// MIME encoded-words in mail headers. None of them is base64.
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"html"
	"mime"
	"mime/quotedprintable"
	"strings"
)

func main() {
	in := `<a href="/?q=1&x=2">Tom & "Jerry"</a>`
	fmt.Println("HTML escape :", html.EscapeString(in))
	fmt.Println("HTML unesc  :", html.UnescapeString("&lt;b&gt; &amp;amp; &#1587;&#x644; &eacute;"))

	// JSON escapes are for the JSON string boundary: quote, backslash, control chars.
	v := map[string]string{"s": "line1\nline2 \"q\" <tag> & 
 سلام"}
	b, _ := json.Marshal(v)
	fmt.Println("json default:", string(b))
	var buf bytes.Buffer
	enc := json.NewEncoder(&buf)
	enc.SetEscapeHTML(false)
	_ = enc.Encode(v)
	fmt.Print("json no-HTML:", " ", buf.String())

	// Quoted-printable: readable text stays readable, other bytes become =XX.
	var qp bytes.Buffer
	w := quotedprintable.NewWriter(&qp)
	_, _ = w.Write([]byte("Café = 5€, " + strings.Repeat("long ", 20)))
	_ = w.Close()
	fmt.Println("\nquoted-printable:")
	fmt.Print(qp.String(), "\n")

	// RFC 2047 encoded-words for non-ASCII mail headers: Q (QP-like) and B (base64).
	fmt.Println("subject Q:", mime.QEncoding.Encode("utf-8", "سلام"))
	fmt.Println("subject B:", mime.BEncoding.Encode("utf-8", "سلام"))
	dec := new(mime.WordDecoder)
	s, _ := dec.DecodeHeader("=?utf-8?b?2LPZhNin2YU=?=")
	fmt.Println("decoded   :", s)
}

Real output:

text
HTML escape : &lt;a href=&#34;/?q=1&amp;x=2&#34;&gt;Tom &amp; &#34;Jerry&#34;&lt;/a&gt;
HTML unesc  : <b> &amp; سل é
json default: {"s":"line1\nline2 \"q\" <tag> & 
 سلام"}
json no-HTML: {"s":"line1\nline2 \"q\" <tag> & 
 سلام"}

quoted-printable:
Caf=C3=A9 =3D 5=E2=82=AC, long long long long long long long long long long=
 long long long long long long long long long long=20
subject Q: =?utf-8?q?=D8=B3=D9=84=D8=A7=D9=85?=
subject B: =?utf-8?b?2LPZhNin2YU=?=
decoded   : سلام
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

/** Encodings that guard other boundaries: HTML, JSON, MIME headers, domains. */
final class Boundaries
{
    public static function demo(): void
    {
        $in = '<a href="/?q=1&x=2">Tom & "Jerry"</a>';

        // HTML boundary. ENT_QUOTES also escapes the single quote; always pass the charset.
        echo htmlspecialchars($in, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), PHP_EOL;

        // JSON boundary: PHP escapes "/" and non-ASCII by default; both flags are readability choices.
        echo json_encode(['s' => "line1\nline2 \"q\" <tag> / سلام"]), PHP_EOL;
        echo json_encode(['s' => "line1\nline2 \"q\" <tag> / سلام"], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), PHP_EOL;
        echo json_encode(['s' => '<tag> & "q"'], JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT), PHP_EOL; // safe inside HTML

        // Quoted-printable (MIME body) and RFC 2047 encoded-words (MIME header).
        echo quoted_printable_encode("Café = 5€"), PHP_EOL;                 // Caf=C3=A9 =3D 5=E2=82=AC
        echo mb_encode_mimeheader('سلام', 'UTF-8', 'B'), PHP_EOL;           // =?UTF-8?B?2LPZhNin2YU=?=

        // Domain boundary (ext-intl): Unicode host <-> xn-- host.
        echo idn_to_ascii('مثال.ایران', IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46), PHP_EOL;
        echo idn_to_utf8('xn--mgbh0fb.xn--mgba3a4f16a', IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46), PHP_EOL;
    }
}

Problem 10: JWT, Basic auth and Kubernetes Secrets ​

go
// Command tokens decodes the three base64 payloads a developer inspects
// most often: a JWT (base64url, no padding), a Kubernetes Secret value
// (standard base64) and an HTTP Basic Authorization header.
package main

import (
	"bufio"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strings"
)

func b64u(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }

// makeJWT builds an HS256 token by hand so the three segments are visible.
func makeJWT(secret []byte, claims map[string]any) string {
	header, _ := json.Marshal(map[string]string{"alg": "HS256", "typ": "JWT"})
	payload, _ := json.Marshal(claims)
	signingInput := b64u(header) + "." + b64u(payload)
	mac := hmac.New(sha256.New, secret)
	mac.Write([]byte(signingInput))
	return signingInput + "." + b64u(mac.Sum(nil))
}

// inspectJWT decodes header and payload WITHOUT verifying the signature.
func inspectJWT(tok string) {
	parts := strings.Split(tok, ".")
	if len(parts) != 3 {
		fmt.Println("not a compact JWS")
		return
	}
	for i, name := range []string{"header", "payload"} {
		raw, err := base64.RawURLEncoding.DecodeString(parts[i])
		fmt.Printf("%-8s %s  (err=%v)\n", name, raw, err)
	}
	sig, _ := base64.RawURLEncoding.DecodeString(parts[2])
	fmt.Printf("%-8s %d bytes (HMAC-SHA256 output)\n", "sig", len(sig))
}

// k8sSecret is the part of `kubectl get secret -o json` we care about.
type k8sSecret struct {
	Data map[string][]byte `json:"data"` // encoding/json decodes std base64 into []byte
}

func main() {
	tok := makeJWT([]byte("demo-secret"), map[string]any{"sub": "42", "name": "مرتضی", "iat": 1764000000})
	fmt.Println("JWT:", tok)
	inspectJWT(tok)

	// HTTP Basic: base64("user:password"), RFC 7617. This is NOT encryption.
	req, _ := http.NewRequest("GET", "https://example.test/", nil)
	req.SetBasicAuth("morteza", "p@ss:word")
	hdr := req.Header.Get("Authorization")
	fmt.Println("\nAuthorization:", hdr)
	raw, _ := base64.StdEncoding.DecodeString(strings.TrimPrefix(hdr, "Basic "))
	fmt.Printf("decoded      : %s\n", raw)

	// Kubernetes Secret JSON on stdin (optional).
	if fi, _ := os.Stdin.Stat(); fi.Mode()&os.ModeCharDevice == 0 {
		var s k8sSecret
		if err := json.NewDecoder(bufio.NewReader(os.Stdin)).Decode(&s); err == nil {
			fmt.Println("\nKubernetes Secret keys decoded:")
			for k, v := range s.Data {
				fmt.Printf("  %-10s = %q\n", k, v)
			}
		}
	}
}

Real output (with kubectl create secret ... --dry-run=client -o json | go run ./tokens):

text
JWT: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3NjQwMDAwMDAsIm5hbWUiOiLZhdix2KrYttuMIiwic3ViIjoiNDIifQ.D7xYjF12Q1bFykenEVYi8222lSfbHXYUMlrYkUgtPNA
header   {"alg":"HS256","typ":"JWT"}  (err=<nil>)
payload  {"iat":1764000000,"name":"مرتضی","sub":"42"}  (err=<nil>)
sig      32 bytes (HMAC-SHA256 output)

Authorization: Basic bW9ydGV6YTpwQHNzOndvcmQ=
decoded      : morteza:p@ss:word

Kubernetes Secret keys decoded:
  password   = "p@ss/w+rd"
php
<?php

declare(strict_types=1);

namespace App\Support\Encoding;

/** Decode the three base64 payloads a developer inspects most often. */
final class Tokens
{
    /** @return array{header: array, payload: array} NOT verified: never trust this for auth. */
    public static function inspectJwt(string $jwt): array
    {
        [$h, $p] = array_slice(explode('.', $jwt), 0, 2);

        return [
            'header'  => json_decode((string) Encodings::base64UrlDecode($h), true, flags: JSON_THROW_ON_ERROR),
            'payload' => json_decode((string) Encodings::base64UrlDecode($p), true, flags: JSON_THROW_ON_ERROR),
        ];
    }

    /** HTTP Basic (RFC 7617): base64("user:password"). Encoding, not encryption. */
    public static function basicAuthHeader(string $user, string $password): string
    {
        return 'Basic ' . base64_encode($user . ':' . $password);
    }

    /** @return array{0: string, 1: string} */
    public static function parseBasic(string $header): array
    {
        $decoded = base64_decode(substr($header, 6), strict: true);
        // The first colon separates user from password; the password may contain colons.
        return $decoded === false ? ['', ''] : explode(':', $decoded, 2) + [1 => ''];
    }

    /**
     * Kubernetes Secret .data values are standard base64 of the raw bytes;
     * a trailing newline from `echo` is a classic source of login failures.
     *
     * @param array<string, string> $data the "data" map of a Secret manifest
     * @return array<string, string>
     */
    public static function decodeSecretData(array $data): array
    {
        return array_map(static fn (string $v): string => (string) base64_decode($v, true), $data);
    }
}

Problem 11: signed URLs and encoding in Laravel ​

A signed URL carries a hex HMAC over the exact URL string, so any re-encoding after signing invalidates it. Build with the helper; never concatenate.

php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

/**
 * Laravel signed URLs: the signature is the lower-case hex of
 * hash_hmac('sha256', <full URL>, APP_KEY) in the "signature" query
 * parameter (see Illuminate\Routing\UrlGenerator::signedRoute). The URL
 * is encoded by the route helper; never hand-build the query for a signed URL.
 */
final class SignedUrls extends Controller
{
    public function link(): string
    {
        // Parameters are percent-encoded by the URL generator; the signature covers the encoded form.
        return URL::temporarySignedRoute(
            'unsubscribe',
            now()->plus(minutes: 30),
            ['user' => 1, 'email' => 'a+b@example.test'] // "+" is encoded as %2B, so it survives
        );
    }

    public function unsubscribe(Request $request): string
    {
        // The route has ->middleware('signed'); this is the manual equivalent.
        abort_unless($request->hasValidSignature(), 403);

        return 'ok';
    }
}

Problem 12: choosing a size budget (benchmark) ​

go
package bench

import (
	"encoding/base64"
	"encoding/hex"
	"math/rand"
	"testing"
)

var payload = func() []byte {
	b := make([]byte, 1<<20)
	rand.New(rand.NewSource(1)).Read(b)
	return b
}()

func BenchmarkBase64Encode(b *testing.B) {
	dst := make([]byte, base64.StdEncoding.EncodedLen(len(payload)))
	b.SetBytes(int64(len(payload)))
	for i := 0; i < b.N; i++ {
		base64.StdEncoding.Encode(dst, payload)
	}
}

func BenchmarkBase64Decode(b *testing.B) {
	enc := make([]byte, base64.StdEncoding.EncodedLen(len(payload)))
	base64.StdEncoding.Encode(enc, payload)
	dst := make([]byte, base64.StdEncoding.DecodedLen(len(enc)))
	b.SetBytes(int64(len(payload)))
	for i := 0; i < b.N; i++ {
		if _, err := base64.StdEncoding.Decode(dst, enc); err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkBase64EncodeToString(b *testing.B) {
	b.SetBytes(int64(len(payload)))
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		_ = base64.StdEncoding.EncodeToString(payload)
	}
}

func BenchmarkHexEncode(b *testing.B) {
	dst := make([]byte, hex.EncodedLen(len(payload)))
	b.SetBytes(int64(len(payload)))
	for i := 0; i < b.N; i++ {
		hex.Encode(dst, payload)
	}
}
text
BenchmarkBase64Encode-10            	     200	    350122 ns/op	2994.88 MB/s
BenchmarkBase64Decode-10            	     200	    299048 ns/op	3506.38 MB/s
BenchmarkBase64EncodeToString-10    	     200	    412536 ns/op	2541.78 MB/s	 2801701 B/op	       2 allocs/op
BenchmarkHexEncode-10               	     200	    486976 ns/op	2153.24 MB/s

Problem 13: how much does an image cost? ​

go
// Command sizes prints how many bytes a file (or a string) becomes under
// each encoding. Usage: sizes -file logo.png   or   sizes -text "سلام"
package main

import (
	"encoding/base64"
	"encoding/hex"
	"flag"
	"fmt"
	"net/url"
	"os"
)

func main() {
	file := flag.String("file", "", "path of a file to measure")
	text := flag.String("text", "", "a string to measure (UTF-8)")
	flag.Parse()

	var raw []byte
	switch {
	case *file != "":
		b, err := os.ReadFile(*file)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		raw = b
	case *text != "":
		raw = []byte(*text)
	default:
		flag.Usage()
		os.Exit(2)
	}

	fmt.Printf("%-16s %10s %8s\n", "encoding", "bytes", "ratio")
	row := func(name string, n int) {
		fmt.Printf("%-16s %10d %7.3fx\n", name, n, float64(n)/float64(len(raw)))
	}
	row("raw", len(raw))
	row("hex", hex.EncodedLen(len(raw)))
	row("base64", base64.StdEncoding.EncodedLen(len(raw)))
	row("base64 raw", base64.RawStdEncoding.EncodedLen(len(raw)))
	row("base64url raw", base64.RawURLEncoding.EncodedLen(len(raw)))
	row("percent (query)", len(url.QueryEscape(string(raw))))
	row("data URI (b64)", len("data:application/octet-stream;base64,")+base64.StdEncoding.EncodedLen(len(raw)))
}

Choosing ​

SituationRecommendedExtra techniqueReason
Binary in a JSON/XML body (API)standard Base64prefer multipart/binary for files over about 100 KBuniversally supported, +33%
Token, ID, hash in a URL, cookie, filenamebase64url, no paddinglength cap; compare in constant timeno + / = to escape
Value a person will read aloud or typeCrockford Base32 or Base58group in fours, add a check symbolremoves look-alike characters
TOTP/2FA secretRFC 4648 Base32uppercase, strip spaces and =what authenticator apps expect
Debugging, hashes, byte dumpshexgroup by 2 or 4clearest, 2x
Smallest text form of 4-byte blocks, in a file formatAscii85 or Z85not in HTML/JSON1.25x
User text in a URL queryurl.Values, http_build_queryUTF-8 first+ and & handled
User text in a URL path segmentPathEscape, rawurlencodeper segment%20, %2F
Domain names with Persian lettersIDNA to xn--UTS #46 profile; show Unicode in UIDNS carries ASCII
Small icon in HTML or CSSdata: URICSP img-src data:one fewer request
Large or reused imagefile or object storage URLCDN and cache headerscaching beats inlining
Secret storagereal encryption (KMS, AES-GCM)not encodingencoding is reversible by everyone
Binary between services you ownbytes (Protobuf, gRPC, multipart)base64 only at JSON edgessaves 33% CPU and bandwidth

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

One Laravel app renders HTML, reads cookies and builds links, and the encodings are mostly invisible: Blade's double-brace echo escapes HTML, route() percent-encodes parameters, and the framework's own encrypted values are Base64 (the Encrypter source calls base64_encode on a JSON payload holding iv, value, mac and tag). The bugs show up at the edges: an avatar posted as a data: URI, a reset link with a Base64 token containing +, a CSV with Persian text in the wrong charset. Everyday example: a password-reset e-mail. Generate 32 random bytes, put rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=') in the URL, store hash('sha256', $bytes) as hex in the database, compare with hash_equals. The arithmetic shows why plain Base64 is a trap here: 32 bytes are 43 Base64 characters, each is + with probability 1/64, so the chance of at least one + is 1 - (63/64)^43, about 49%: roughly every second link would break if + were turned into a space. Production example (checkable): Laravel's signed URLs append signature= plus the lower-case hex of hash_hmac('sha256', <url>, <key>) (UrlGenerator::signedRoute), deliberately hex so no URL-significant character can appear.

Modular monolith / multiple databases ​

Modules agree on formats at their boundaries: an Identity module issues JWTs (base64url), a Billing module stores invoice PDFs as bytea or in object storage, a Notifications module builds MIME messages (Base64 attachments, quoted-printable bodies). Keep each encoder in one place (one Encodings class or Go package) and expose typed values (SignedToken, ContentHash) so nobody passes "some base64 string" around. Everyday example: invoice_pdf_sha256 stored as 32 raw bytes in a bytea column, shown as hex in the admin UI, and as base64url in a download URL: three views of one value, one source of truth. Production example (checkable): PostgreSQL itself separates storage from text form: the documentation shows decode('MTIzAAE=', 'base64') returning the hex-format bytea \x3132330001, and encode(bytea, 'hex' | 'base64' | 'escape') as explicit conversions (PostgreSQL binary string functions); store bytes, convert at the edge.

Microservices ​

Between services, text encodings multiply: JSON carries binary as Base64, headers carry JWTs, queues carry envelopes. Rules that keep it sane: (1) write the alphabet and padding into the API contract (OpenAPI 3.1 uses JSON Schema's contentEncoding: base64; 3.0 used format: byte; there is no standard name for base64url, so state it in the description); (2) prefer binary protocols for payloads over about 100 KB: Protobuf bytes, gRPC streaming, multipart (see Serialization Formats); (3) put correlation data in headers as plain text and signatures as base64url; (4) pass URLs encoded once and decode once per hop, never in the gateway and again in the service.

text
browser ── POST /v1/avatars  {"image":"<base64>"}  ──▶ gateway (route-specific body cap)
gateway ── Authorization: Bearer <b64url.b64url.b64url> ──▶ avatar-svc
avatar-svc ── decode strictly, cap decoded size, sniff magic bytes ──▶ object storage (raw bytes)
avatar-svc ── event {"key":"avatars/9f2c.../1.png","sha256":"9f2c..."} ──▶ queue   (hex hash, no payload)

Everyday example: an API returns an image_base64 field of 200 KB; the mobile app decodes it. Replacing it with a pre-signed URL removes the encoding, the 33%, and the memory spike. Production example (checkable): the Protocol Buffers JSON mapping defines a bytes field as a Base64 string ("JSON value will be the data encoded as a string using standard base64") and its parsers accept both alphabets, so a gRPC service exposed through a JSON gateway carries every binary field at +33%.

Distributed data (replicas, caches, CDNs) ​

Encoding becomes part of identity: cache keys, CDN URLs and shard keys are strings, so two spellings of one value are two keys. RFC 3986 says URIs that differ only in the case of hex digits in a percent-encoding are equivalent, but a cache keyed on the raw string stores %d8%b3 and %D8%B3 separately unless the CDN or your code normalises; + versus %20 and padded versus unpadded Base64 create more duplicates. Everyday example: a Redis cache key built from a JSON filter: normalise the JSON, hash it, use lower-case hex or base64url without padding, and the same filter always hits the same key. Production example (checkable): Git LFS pointer files (specification section "The Pointer") are text of version, oid sha256:<64 hex digits> and size, "unique: there is exactly one valid encoding for a pointer file", and under 1024 bytes: a content-addressed identity that is deliberately canonical so every replica computes the same bytes. Replicas replicate bytes, not encodings: a bytea column is half the size of its Base64 text and avoids the question of which spelling was stored.

Scaling path ​

LoadWhat changes
1x (hundreds of requests per second)Standard libraries; encode in the handler; base64 in JSON is fine
10xStop base64-ing files in JSON: use upload URLs and streaming; use AppendEncode-style APIs and pooled buffers; cap sizes at the edge
100xBinary protocols between services; CDN for images; normalise URLs at the edge (lower-case percent hex, one +/%20 policy) so caches hit; SIMD-accelerated Base64 where it shows in profiles
Multi-regionKeep encodings in the contract, version them, and test with a golden vector file (known inputs and outputs) in every language you ship

Troubleshooting ​

SymptomLikely causeCheckFix
Token verifies locally, fails after a redirect or e-mail link+ became a space, or = was droppedcompare the received query string byte by bytepercent-encode, or switch to base64url
illegal base64 data at input byte N (Go)wrong variant (padded vs raw, std vs url)look for -, _, missing =choose the matching Encoding; normalise
Decoded text has a trailing newline (...\n)echo added a newline before base64echo -n or printfuse printf '%s'; check Kubernetes Secret values with base64 -d | xxd
Login to a service fails with a "correct" Kubernetes Secretnewline inside the encoded valuekubectl get secret x -o jsonpath='{.data.k}' | base64 -d | xxd | tailrecreate with --from-literal or echo -n
InvalidCharacterError from btoastring contains characters above 0xFFcontains Persian or emojiTextEncoder to UTF-8 bytes, then Base64
Persian text shows سلامUTF-8 bytes decoded as Latin-1 after Base64check charsetdecode bytes as UTF-8
%2520 in a URLdouble encodingdecode once and look againencode once
400 or 404 only when path has %2Fproxy or server rejects encoded slashesnginx/Apache logschange the identifier (base64url) or the server setting
Image does not show in e-mailclient blocks data: imagestest in Gmail/Outlookuse a cid: attachment or a hosted image
CSP violation for an inline imageimg-src lacks data:browser consoleadd data: to img-src only
Laravel signed URL gives 403URL re-encoded, parameter order changed, proxy rewrote the hostcompare the incoming URL with the generated onepass the original query untouched; set trusted proxies
Two services compute different hashes for the "same" stringhex case, padding or line wrap differsnormalise to lower-case hexone canonical form, constant-time compare
Memory spike when encoding an uploadwhole file built as a stringprofileNewEncoder/stream filters
Pasting a key breaks in a chat app= or + reformattedview as plain textuse base64url or hex for pasted secrets

Lab ​

Copy-paste on a Mac or Linux machine; Go 1.24+ is needed for the programs. Run everything from docs/snippets/foundations/binary-to-text-encoding/go.

Lab 1 — compare sizes for a Persian string and an image.

bash
go run ./encodings
# expected: the table in Problem 1: hex 34, base64 24, base64url raw 23, percent 49-51 for 17 bytes
head -c 3000 /dev/urandom > /tmp/blob.bin
go run ./sizes -file /tmp/blob.bin
# expected: raw 3000, hex 6000 (2.000x), base64 4000 (1.333x), base64 raw 4000, base64url raw 4000, percent about 8000+, data URI 4037
go run ./sizes -text "سلام دنیا"
# expected: raw 17, hex 34, base64 24, base64url raw 23, percent (query) 49

Lab 2 — reproduce the + to space bug and fix it.

bash
go run ./urlbug
# expected: "server sees: \"    //4=\" (same as sent? false)" then the fixed URL with %2B and "same as sent? true"
curl -sG -o /dev/null -w '%{url_effective}\n' --data-urlencode 'q=a+b c/d' --data-urlencode 'name=سلام' http://127.0.0.1:1/x
# expected: http://127.0.0.1:1/x?q=a%2bb+c%2fd&name=%d8%b3%d9%84%d8%a7%d9%85   (curl uses lower-case hex)
python3 -c "import urllib.parse as u; print(u.quote('a b+c/d'), u.quote_plus('a b+c/d'), u.unquote_plus('a+b%2Bc'))"
# expected: a%20b%2Bc/d a+b%2Bc%2Fd a b+c

Lab 3 — inspect a JWT.

bash
T=$(go run ./tokens | sed -n 1p | cut -d' ' -f2)
echo $T | cut -d. -f1 | base64 -d; echo
# expected: {"alg":"HS256","typ":"JWT"}        (works because this segment length needs no padding on this machine)
p=$(echo $T | cut -d. -f2); while [ $(( ${#p} % 4 )) -ne 0 ]; do p="$p="; done
echo $p | tr '_-' '/+' | base64 -d; echo
# expected: {"iat":1764000000,"name":"مرتضی","sub":"42"}

The re-padding loop is the fix for base64: invalid input on unpadded segments; the tr converts base64url back to standard.

Lab 4 — inspect a Kubernetes Secret (no cluster needed).

bash
kubectl create secret generic db --from-literal=username=admin --from-literal=password='p@ss/w+rd' --dry-run=client -o yaml
# expected:
# apiVersion: v1
# data:
#   password: cEBzcy93K3Jk
#   username: YWRtaW4=
# kind: Secret
kubectl create secret generic db --from-literal=password='p@ss/w+rd' --dry-run=client -o jsonpath='{.data.password}' | base64 -d; echo
# expected: p@ss/w+rd
echo hello | base64; printf hello | base64
# expected: aGVsbG8K  then  aGVsbG8=      (the first has a hidden newline: the classic Secret bug)

Lab 5 — hex, Base64 bit layout, Git Base85.

bash
printf 'Man' | xxd -p; printf 'Man' | base64; printf 'Ma' | base64; printf 'M' | base64
# expected: 4d616e   TWFu   TWE=   TQ==
cd /tmp && rm -rf b2t && mkdir b2t && cd b2t && git init -q . && printf '\x00\x01\x02binary\xff' > f.bin && git add f.bin && git -c user.email=a@b -c user.name=a commit -qm one && printf '\x00\x01\x02BINARY\xff\xfe' > f.bin && git diff --binary | sed -n 3,6p
# expected: GIT binary patch / literal 11 / <one Base85 line> (git's own alphabet)

Lab 6 — streaming and the safe decoder.

bash
go build -o /tmp/stream ./stream && /usr/bin/time -l /tmp/stream 2>&1 | egrep "source|sha256|maximum resident"
# expected: source 104857600 bytes, base64+MIME 143489350 bytes (1.368x); sha256 before == after; maximum resident set size about 9.7 MB (9748480 here)
go run ./safedecode
# expected: valid 200, newline injected 400, sloppy trailing bits 400, oversize 413

Common misconceptions ​

BeliefReality
"Base64 encrypts or hides data"It is reversible spelling; RFC 4648: it "does not provide any computational confidentiality"
"Base64 shrinks data"It grows it by a third (hex doubles it); compress first, then encode
"There is one Base64"Standard vs url-safe, padded vs raw, wrapped vs not: five spellings; Go has four Encoding constants for them
"= is part of the data"It is length filler; JWT and many tokens remove it
"+ means space in URLs"Only in form encoding; in a path it is a plus, and RFC 3986 gives it no special meaning in a query
"encodeURI is safe for query values"It leaves & = + # alone; use encodeURIComponent or URLSearchParams for values
"urlencode and rawurlencode are the same"PHP: + versus %20 for space; urlencode also encodes ~
"Encode the whole URL once and it is fine"Encode each component separately, once
"A URL can contain Persian letters"A URI cannot; an IRI can and is mapped to percent-encoded UTF-8; hosts use Punycode
"btoa handles any string"Only characters up to 0xFF; Unicode needs UTF-8 bytes first
"Bigger inline images are faster"data: URIs grow 33%, cannot be cached separately and are blocked by strict CSP
"A JWT is encrypted"A JWS is signed; header and payload are base64url, readable by anyone holding the token
"Kubernetes Secrets are secure because they are base64"Base64 is encoding; Secrets are plaintext in etcd unless encryption at rest is on
"If the decoder accepts it, it is valid"Lenient decoders drop junk, accept the other alphabet and ignore non-zero pad bits
"Hex case does not matter for security"RFC 4648 warns case alteration can be used to make string comparisons fail; normalise first

Cheat sheet ​

TopicWhat to remember
Base64 size3 bytes to 4 chars, 4*ceil(n/3), +33%; MIME wrap adds CRLF every 76 (about 1.37x)
Base64 alphabetsA-Za-z0-9+/ and =; url-safe A-Za-z0-9-_
Where padding is droppedJWT (JWS), many URL tokens: RFC 4648 allows when the length is implicit
JWTthree base64url segments joined by .; eyJ starts a JSON object; signed, not encrypted
Hex2 chars per byte, 2x, case-insensitive; compare in constant time
Base32A-Z2-7, 1.6x, case-insensitive; TOTP secrets; Crockford drops ILOU
Base58Bitcoin alphabet without 0OIl+/; big-integer maths; short values only
Base855 chars per 4 bytes, 1.25x; Ascii85 in PDF; Git has its own alphabet
Unreserved charactersA-Z a-z 0-9 - . _ ~; encode everything else per component
+ vs %20+ is a space only in form encoding; always encode query values
Double encodingencode once, decode once; %25 is the sign of a second pass
IRI and IDNAbrowsers map Persian URLs to UTF-8 %XX paths and xn-- hosts
Data URIdata:<type>;base64,<data>; only small assets; CSP img-src data:
Decoding untrusted inputcap length first, decode strictly, verify content type, cap decoded size
Not encryptionBase64, hex, percent, Basic, Kubernetes data: are all readable without a key
Gobase64.StdEncoding, RawURLEncoding, url.Values, hex, NewEncoder for streams
PHP and Laravelbase64_decode($s, true), rawurlencode, http_build_query, Str::toBase64, signed URLs

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does Base64 output grow by about 33%, and what is the exact length for 10 input bytes? Must-know ​

Answer

Answer: Every 3 bytes (24 bits) become 4 characters of 6 bits. For 10 bytes: 4 * ceil(10 / 3) = 16 characters padded (ceil(40/3) = 14 without padding).

2 — A signed token works in JSON but fails in a link from e-mail. Which two bytes are the first suspects? Important ​

Answer

Answer: + (turned into a space by form decoding) and = (padding that got stripped or percent-encoded). Use base64url without padding or percent-encode the value.

3 — What is the difference between urlencode and rawurlencode in PHP and between QueryEscape and PathEscape in Go? Important ​

Answer

Answer: urlencode and QueryEscape use form rules (space becomes +); rawurlencode and PathEscape produce %20. PHP urlencode also encodes ~.

4 — Why does btoa('سلام') throw, and how do you fix it? Must-know ​

Answer

Answer: btoa treats each character code as one byte and rejects code points above 0xFF. Convert the string to UTF-8 bytes with TextEncoder and Base64 the bytes.

5 — Is a JWT payload secret? Why or why not? Must-know ​

Answer

Answer: No. A normal JWT (JWS) is signed and base64url-encoded; anyone holding it can decode the payload. Only the signature protects integrity. JWE would be needed for confidentiality.

6 — How does a Kubernetes Secret value cEBzcy93K3Jk relate to the real secret and who can read it? Must-know ​

Answer

Answer: It is standard Base64 of the raw bytes (p@ss/w+rd). Anyone who can read the Secret object, or etcd if encryption at rest is off, can decode it with base64 -d.

7 — What is double encoding and how does it turn into a security bug? Important ​

Answer

Answer: Encoding or decoding twice (%2520). A filter decodes once and sees safe text; the application decodes again and gets ../ or a script. Decode exactly once at the boundary.

8 — Why is aGl= accepted by some decoders and rejected by Go Strict()? Good to know ​

Answer

Answer: Its last character carries non-zero pad bits; the canonical form is aGk=. Lenient decoders ignore the bits; strict ones reject them. Ambiguity breaks string comparisons of encoded values.

9 — When is a data: URI a good idea and when is it a bad one? Good to know ​

Answer

Answer: Good for tiny one-off assets (icons, placeholders, e-mail inline images where supported). Bad for large or reused images: +33%, no separate caching, CSP must allow data:, some e-mail clients block it.

10 — What encoding does the host مثال.ایران take on the wire, and the path /مقاله? Important ​

Answer

Answer: The host uses IDNA/Punycode (xn--mgbh0fb.xn--mgba3a4f16a); the path is UTF-8 bytes percent-encoded (%D9%85%D9%82%D8%A7%D9%84%D9%87).

11 — How do you accept a base64 avatar from an untrusted client safely? Must-know ​

Answer

Answer: Cap the encoded length before decoding, decode strictly, reject whitespace you do not expect, cap the decoded size, then verify magic bytes and re-process the image. Never trust the declared type.

12 — Why does echo hello | base64 give a different value from printf hello | base64? Must-know ​

Answer

Answer: echo appends a newline byte, so the encoded input is hello\n (aGVsbG8K). It is the usual cause of passwords with a hidden newline in Kubernetes Secrets.

Glossary ​

TermOne line
Binary-to-text encodingA reversible mapping of arbitrary bytes onto a restricted printable alphabet
AlphabetThe set of characters an encoding may output
QuantumRFC 4648 term for the input group that maps to one output unit (3 bytes for Base64)
Base16 / hex4 bits per character, 0-9A-F
Base325 bits per character, A-Z2-7, case-insensitive
base32hexBase32 with 0-9A-V so order is preserved
Crockford Base32Base32 without I L O U, tolerant decoding, optional check symbol
z-base-32Human-oriented Base32 with a reordered lower-case alphabet
Base58Big-integer base with no 0 O I l + /; Bitcoin alphabet
Base58CheckBase58 plus a 4-byte double-SHA-256 checksum
Base646 bits per character, A-Za-z0-9+/
Base64urlBase64 with - and _; RFC 4648 section 5
Padding (=)Filler making the output a multiple of 4 (Base64) or 8 (Base32) characters
Raw / unpaddedBase64 without =, as used by JWT
MIME line wrappingLines of at most 76 characters separated by CRLF
Pad bitsUnused low bits in the last character; must be zero in canonical form
Strict decodingRejecting input with non-alphabet characters, wrong padding or non-zero pad bits
Forgiving-base64The WHATWG decode used by atob: strips whitespace, tolerates missing padding
Ascii85 / Base855 characters per 4 bytes; Adobe, Git, RFC 1924 and Z85 variants
uuencodeUnix-to-Unix encoding, 1980s ancestor of Base64
Quoted-printableMIME encoding that keeps printable ASCII and writes other bytes as =XX
Encoded-wordRFC 2047 syntax =?charset?B or Q?text?= for non-ASCII mail headers
Percent-encoding%XX for a byte; RFC 3986 pct-encoded
Unreserved charactersA-Z a-z 0-9 - . _ ~: never need encoding
Reserved charactersgen-delims and sub-delims: delimiters with meaning inside a URL
application/x-www-form-urlencodedForm encoding where space is + and + is decoded as space
Double encodingEncoding an already-encoded value, producing %25 sequences
URI / URLAn ASCII identifier; URL is a URI that locates
IRIURI that may contain Unicode characters (RFC 3987), mapped to a URI
IDNAInternationalized Domain Names in Applications
PunycodeRFC 3492 ASCII form of Unicode labels, prefixed xn--
Data URIdata: URL with inline data (RFC 2397)
CSPContent-Security-Policy; img-src must allow data: for inline images
JWS / JWTSigned token: three base64url segments joined by .
HTTP BasicAuthorization: Basic + Base64 of user:password
HTML entity&amp;, &#x633;: HTML's escape syntax
JSON escape\", \\, \n, \uXXXX in a JSON string
ObfuscationMaking data look unreadable without a key; not security
SIMD base64Vectorised encoders/decoders (AVX2, AVX-512, NEON) that approach memcpy speed
Git LFS pointerSmall text file with version, oid sha256: and size that stands in for a large file
TOTP secretBase32-encoded key in otpauth:// URIs

References ​

All fetched and read on 2026-11-25; local copies saved under the author's scratchpad sources/binary-to-text-encoding/. Each link returned HTTP 200.

Built by Morteza Negahi