Back to all posts
Tutorial
7 min read

How to Decode Base64 in Terminal and Code

DevToolLab Team

DevToolLab Team

December 2, 2026

How to Decode Base64 in Terminal and Code

To decode Base64 in a terminal, pipe it into base64 -d (also spelled base64 --decode) on macOS or Linux. In Python call base64.b64decode(), in Node.js use Buffer.from(text, "base64"), and in a modern browser use Uint8Array.fromBase64() or the older atob(). Decoding always gives you bytes: whether they are text, an image or a ZIP file depends on what was encoded.

The tricky part is everything around the string: line breaks, the URL-safe alphabet, missing = padding and data: prefixes. Decoders disagree on how to handle them. Some throw an error, and some quietly return wrong output, which is worse.

The Fastest Way

For text, paste the string into the Base64 Encoder Decoder. For anything that is really a file, such as an image, a PDF or a ZIP that an API sent back as text, use File to Base64: paste the Base64 or a full data URI, press Decode to File, and it reads the real file type from the decoded bytes, shows a preview and downloads the file with the right extension. Both run in your browser and send nothing to a server.

What neither tool does is decrypt anything. Base64 is an encoding, not encryption, so if a string decodes to random-looking bytes, the data inside was probably encrypted or compressed before it was encoded.

How to Decode Base64 in the Terminal

On macOS and Linux the command is the same:

Bash
$ echo 'aGVsbG8gZnJvbSBBdXN0aW4sIFRYCg==' | base64 -d
hello from Austin, TX

Linux ships the GNU coreutils version. Its manual documents -d/--decode plus -i/--ignore-garbage, which skips bytes outside the Base64 alphabet, and says newlines are always accepted when decoding. The built-in base64 on macOS 27 takes the same -d (it also accepts -D), but its -i and -o name the input and output files, so -i means something different on each system.

Here is a real example that most developers hit eventually. GitHub's repository contents API returns files with "encoding": "base64", so reading a README through the API means decoding it:

Bash
$ curl -s https://api.github.com/repos/curl/curl/contents/README | jq -r .content | base64 -d | head -8
                                  _   _ ____  _
                              ___| | | |  _ \| |
                             / __| | | | |_) | |
                            | (__| |_| |  _ <| |___
                             \___|\___/|_| \_\_____|

README

The content field arrives wrapped in lines of 60 characters (we counted 32 full lines for this file on December 2, 2026), and base64 -d reads straight through the line breaks.

On Windows, certutil -decode in.txt out.bin decodes a file, according to Microsoft's certutil reference, and in PowerShell [Convert]::FromBase64String($b64) returns the bytes. We did not run these two for this post.

How to Decode Base64 in Python

The standard library's base64 module does the work. The same GitHub file, decoded in Python 3.13:

Python
import base64, json, urllib.request

with urllib.request.urlopen("https://api.github.com/repos/curl/curl/contents/README") as r:
    data = json.load(r)

raw = base64.b64decode(data["content"])  # the API wraps lines at 60 chars; b64decode skips the newlines
print(data["encoding"], len(raw), "bytes")
print(raw.decode("utf-8").splitlines()[6])
Bash
$ python3 decode_readme.py
base64 1461 bytes
README

The decoded length, 1,461 bytes, matches the size field the API reports, which is a cheap way to confirm a decode was complete. If you want Python to reject bad input instead of skipping it, pass validate=True, but strip whitespace first: with validate=True, a newline alone raises binascii.Error: Only base64 data is allowed. For URL-safe strings that use - and _, call base64.urlsafe_b64decode().

How to Decode Base64 in JavaScript

In Node.js, Buffer has decoded Base64 for years:

js
const res = await fetch("https://api.github.com/repos/curl/curl/contents/README")
const { content } = await res.json()

const bytes = Buffer.from(content, "base64") // Node: skips the newlines, but also any other junk
console.log(bytes.length, "bytes")
console.log(bytes.toString("utf8").split("\n")[6])
$ node decode_readme.mjs
1461 bytes
README

Pass "base64url" instead of "base64" for the URL-safe alphabet. The newer option is Uint8Array.fromBase64(), which MDN lists as Baseline 2025, available across current browsers since September 2025. It works in both Node 26.12 and Chrome 158 in our tests, returns real bytes rather than a string, and throws on bad characters instead of skipping them. In older browsers, atob() decodes to a "binary string" with one character per byte; run it through TextDecoder if the content is UTF-8 text, or accented characters will come out mangled.

Decode Base64 to a File

When the Base64 is an image or a document, write the bytes to disk instead of printing them. With a data URI, cut off everything up to the comma first. This uses the 96 x 96 PNG that File to Base64 ships as its example:

Bash
DATA=$(cat logo.datauri.txt)          # data:image/png;base64,iVBORw0KGgo...
printf '%s' "${DATA#*,}" | base64 -d > logo.png
file logo.png
Bash
logo.png: PNG image data, 96 x 96, 2-bit colormap, non-interlaced

The Python version splits the header from the data and writes bytes:

Python
import base64, pathlib

data_uri = pathlib.Path("logo.datauri.txt").read_text()
header, b64 = data_uri.split(",", 1)           # "data:image/png;base64", "iVBORw0KGgo..."
pathlib.Path("logo-py.png").write_bytes(base64.b64decode(b64, validate=True))
print(header, "->", pathlib.Path("logo-py.png").stat().st_size, "bytes")
Bash
$ python3 tofile.py
data:image/png;base64 -> 214 bytes

Both files came out byte-for-byte identical. If you do not know what kind of file a Base64 string holds, the file's first bytes usually tell you: a PNG starts with 89 50 4E 47, a PDF with %PDF-, a ZIP with PK. That is the check File to Base64 runs before it names the download.

Common Errors

binascii.Error: Incorrect padding (Python). The string lost its trailing = signs, which happens when Base64 travels through URLs or gets trimmed. Add them back before decoding with s += "=" * (-len(s) % 4). In our tests Python also raised this same message for a string containing an invalid character, so check for stray characters too.

Invalid base64-encoded string: number of data characters (5) cannot be 1 more than a multiple of 4 (Python). No amount of padding fixes this one: the string was cut off mid-copy. Get the full value again.

Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded. (Chrome). The input has characters outside the standard alphabet. The usual culprits are URL-safe - and _, a leftover data:image/png;base64, prefix, or quotes copied along with the value. Node.js reports the same problem as InvalidCharacterError: Invalid character.

No error, wrong output. This is the dangerous case. Python's b64decode("-_-_") returns b'' without complaint, Node's Buffer skips characters it does not recognize, and macOS's base64 -d stopped at the first invalid character and still exited with status 0 in our test, untill you notice the file is short. Use validate=True, urlsafe_b64decode() or Uint8Array.fromBase64() when correctness matters, and compare the decoded length to whatever size the sender reports.

When Not to Do This

Do not paste secrets into an online decoder that sends input to a server. Kubernetes Secrets, JWT payloads and HTTP Basic auth headers are all Base64, and decoding them in a tool that logs requests hands the credentials to a third party. Decode them locally or in a browser-only tool, and remember the flip side: since anyone can decode Base64, encoding a secret never protected it in the first place. Treat Base64 as packaging for bytes, nothing more, and keep real protection in encryption and access control accross your stack.

  • File to Base64 - decode Base64 or a data URI back into the original file, with the file type detected from its bytes and a preview before you download.
  • Base64 Encoder Decoder - decode Base64 text in the browser when the result is a string, not a file.
  • Base64URL Encoder Decoder - handle the URL-safe - and _ alphabet that makes atob() throw.
  • Base64 to Image - preview an image straight from Base64 when you only need to see it, not save it.

Related Posts

How to Add a Drag-and-Drop Email Editor

We can embed a drag-and-drop email editor in a web app with Stripo Plugin, keep the Secret Key on our server and save both editable and compiled HTML.

By DevToolLab Team•

How to Create a Video Using AI for Free

We can create a video using AI for free with a script, a local AI voice and a code renderer, or let Gemini, Runway or HeyGen build it from a prompt.

By DevToolLab Team•

Git CVE-2026-111760: Check and Patch Git

CVE-2026-111760 lets a malicious repo run code during git clone --recurse-submodules. Check every Git, update to 2.56.1, and patch macOS, Ubuntu and CI.

By DevToolLab Team•