Encoding and security guides

Base64 and UTF-8: decode text without corrupting bytes

Turn text into bytes before Base64 encoding and determine whether decoded bytes are valid UTF-8.

Nav Tools ·

Text needs a character encoding

Base64 transforms bytes. UTF-8 determines which bytes represent a text string, so the two operations answer different questions.

Use a known short Unicode value to check the pipeline. btoa is a binary-string API and cannot accept arbitrary Unicode text directly.

Text:   中文
UTF-8:  e4 b8 ad e6 96 87
Base64: 5Lit5paH

Decode bytes before interpreting them

A valid Base64 value can represent a picture, compressed data or text. Decoding successfully does not identify its file type or character set.

Inspect bytes or the known source format before choosing a text decoder. Replacement characters indicate an interpretation problem, not necessarily broken Base64.

Remove wrappers deliberately

A data URL contains a media type and an encoding marker before its payload. The full data URL is not a bare Base64 string.

Use the image data-URL tool for image workflows. For a bare codec, extract only the payload after the comma when the source is a Base64 data URL.

data:image/png;base64,<payload>
Prefix: data:image/png;base64,
Payload: only the bytes represented after the comma

Compare exact bytes

A text round trip must preserve both characters and the agreed encoding. Binary round trips should compare lengths or hashes of the original bytes.

Base64 is readable by anyone and increases size by roughly one third before transport compression. Choose it for protocol compatibility, not confidentiality or compression.

References

← Encoding and security guides