brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -m base64 -d decodes base64 the same way on every system

Python
~/tips/tip-python-m-base64-decode

echo 'dXNlcjpwYXNz' | python3 -m base64 -d

Encode or decode base64 from the terminal without worrying which base64 tool is installed.

The base64 command differs between Linux and macOS, and its flags have changed over the years. When a script must work on both, I’d use Python’s version instead.

printf 'user:pass' | python3 -m base64
# dXNlcjpwYXNz

echo 'dXNlcjpwYXNz' | python3 -m base64 -d
# user:pass

Without options it encodes, with -d it decodes. It reads standard input, or a file if you give it a name. It’s handy for peeking at a basic auth header copied from a log, a secret value from a Kubernetes manifest, or the middle part of a token.

Notice that I used printf and not echo when encoding. echo adds a newline, which ends up inside the encoded value, so you’d get dXNlcjpwYXNzCg==. That extra Cg== is a classic cause of a password that “looks right” but doesn’t work.

The encoded output is wrapped at 76 characters per line, the old MIME style. For long values that you want on one line, strip the newlines afterwards with tr -d '\n'. It also only handles standard base64, not the URL safe variant with - and _, which you’ll find in JWTs. And base64 is encoding, not encryption: anyone can decode it, so don’t treat an encoded secret as a protected one.

Further reading: base64 module

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link