ShieldX Toolly
Open a tool Donate
Home Home
Blog Blog
FAQ FAQ
Open a tool Donate
Back to cheatsheets
Developer

Base64 Encode / Decode

UTF-8 safe Base64 encoding and decoding, including the URL-safe variant and file conversion.

3 snippets Beginner base64-encoder-decoder
Base64UTF-8encodingURL-safedata URI

What you'll learn

  • UTF-8 safe encode/decode
  • URL-safe Base64
  • File to Base64 data URI

How to use these snippets

  1. Click the Copy button next to any snippet to copy it to your clipboard.
  2. Paste the code into your project, IDE, or terminal.
  3. Replace placeholder values (like example.com or your-secret) with your actual data.
  4. Review the code comments for important security notes and caveats.
  5. Try the interactive related tool to see the concept in action.
Code Snippets

Copy-paste code snippets

3 ready-to-use snippets for base64 encode / decode. Click copy and paste into your project.

UTF-8 safe encode/decode
                function encodeBase64(str) {
  const bytes = new TextEncoder().encode(str);
  return btoa(String.fromCharCode(...bytes));
}
function decodeBase64(b64) {
  const bytes = Uint8Array.from(atob(b64),
    c => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}
              
URL-safe Base64
                function encodeBase64UrlSafe(str) {
  const bytes = new TextEncoder().encode(str);
  return btoa(String.fromCharCode(...bytes))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}
function decodeBase64UrlSafe(b64) {
  const padded = b64
    .replace(/-/g, '+')
    .replace(/_/g, '/');
  while (padded.length % 4) padded += '=';
  const bytes = Uint8Array.from(atob(padded),
    c => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}
              
File to Base64 data URI
                async function fileToBase64(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.readAsDataURL(file);
  });
}
// Result: "data:image/png;base64,iVBORw0KG..."
              
Tool

Try this concept hands-on with the interactive tool.

100% Free · No signup · No cost

Generate something unguessable right now

148 bits of entropy, a crack-time estimate you can trust, and a clipboard that clears itself after 30 seconds.

Open the toolkit

Part of the Toolly ecosystem · secure.toolly.site