How to Convert a String to Base64 and Back (and Why It Matters)

How to Convert a String to Base64 and Back (and Why It Matters)
Photo by @ ghebby / Unsplash

When working with web technologies, file handling, or even data serialization, you’ll eventually come across Base64 encoding. It might look like gibberish at first glance — a long string full of letters, numbers, slashes, and equals signs — but it’s actually a very simple and powerful tool.

Let’s dive into how to convert a string to Base64 and back, why you’d want to do it, and what to watch out for.


✨ What is Base64?

Base64 is a way to encode binary data as ASCII text. It takes any input — whether it’s plain text, a file, or even an image — and converts it into a set of characters that can be safely transmitted or stored using text-based protocols like HTTP, JSON, or XML.

  • Why Base64? Because not all systems or protocols handle binary data well.
  • Why "64"? Because the encoding uses 64 characters: A–Z, a–z, 0–9, +, and /.
Important: Base64 is not encryption. Anyone who gets access to the encoded string can decode it. It’s just an encoding mechanism — like converting a number to hexadecimal or binary.

🔁 Base64 Encoding and Decoding in Practice

1. Encoding a String to Base64

Let’s say you have the string "hello world".

In JavaScript:

const original = "hello world";
const encoded = btoa(original); // "aGVsbG8gd29ybGQ="

In PHP:

$original = "hello world";
$encoded = base64_encode($original); // aGVsbG8gd29ybGQ=

In Go:

import "encoding/base64"

original := "hello world"
encoded := base64.StdEncoding.EncodeToString([]byte(original))
// encoded = "aGVsbG8gd29ybGQ="

In Rust:

use base64::{engine::general_purpose, Engine as _};

let original = "hello world";
let encoded = general_purpose::STANDARD.encode(original);
// encoded = "aGVsbG8gd29ybGQ="
🔍 Tip: Always make sure your string is in UTF-8 format before encoding. Some platforms may throw errors or produce incorrect results for non-ASCII input.

2. Decoding Base64 Back to the Original String

You can reverse the process just as easily.

In JavaScript:

const decoded = atob("aGVsbG8gd29ybGQ"); // "hello world"

In PHP:

$decoded = base64_decode("aGVsbG8gd29ybGQ="); // hello world

In Go:

decodedBytes, _ := base64.StdEncoding.DecodeString("aGVsbG8gd29ybGQ=")
decoded := string(decodedBytes) // "hello world"

In Rust:

let decoded_bytes = general_purpose::STANDARD.decode("aGVsbG8gd29ybGQ=").unwrap();
let decoded = String::from_utf8(decoded_bytes).unwrap(); // "hello world"

🧠 Considerations You Might Miss

🔐 1. Base64 is not secure

Don’t use Base64 thinking it's encryption. It’s trivially reversible. Anyone can decode it in seconds. If you need to secure data, use AES, RSA, or other cryptographic techniques.


⚠️ 2. Output Size Increases

Base64 output is ~33% larger than the original data. If you’re encoding large files or binary blobs, this can be a significant storage or bandwidth cost.


📤 3. Use it for Transport, Not Storage

Base64 is often used in scenarios like:

  • Embedding images in HTML (<img src="data:image/png;base64,...">)
  • Sending binary data in JSON or XML
  • Encoding credentials in HTTP headers (Authorization: Basic base64(username:password))

But for long-term storage of large content, consider storing raw binary.


🧱 4. Variants Exist

Some contexts require URL-safe Base64 (replaces + with - and / with _), such as:

  • JWT tokens
  • Web-safe data URIs

In Go:

base64.URLEncoding.EncodeToString([]byte(data))

In JavaScript, you may need to manually replace characters.


🧪 5. Validate Before Decoding

If you’re receiving Base64 from an external source, validate it:

  • Ensure it’s not malformed
  • Handle padding correctly (= at the end)
  • Catch decoding errors gracefully

🧩 Summary

Here’s a quick summary table:

Action JavaScript PHP Go Rust
Encode Base64 btoa(str) base64_encode($str) base64.StdEncoding.EncodeToString([]byte(str)) base64::encode(str)
Decode Base64 atob(str) base64_decode($str) base64.StdEncoding.DecodeString(str) base64::decode(str) + UTF-8

✅ Finally

Base64 is a useful and simple tool for encoding data that must travel safely through systems that can only handle plain text. Just remember:

  • It’s not encryption.
  • It increases data size.
  • It’s perfect for short-term transport, not for long-term storage of binary data.

Understanding how to use Base64 — and more importantly, when to use it — is a key skill in modern software development.

Support Us