Python में Base64 Decode — b64decode()

·Backend Developer·समीक्षकDmitri Volkov·प्रकाशित

मुफ़्त Base64 Decode Online को सीधे अपने ब्राउज़र में उपयोग करें — इंस्टॉलेशन की ज़रूरत नहीं।

Base64 Decode Online ऑनलाइन आज़माएं →

जब कोई API एक content field लौटाए जो eyJob3N0IjogImRiLXByb2Qi… जैसी दिखे, या आपका secrets manager एक encoded credential दे, या आपको JWT payload निकालनी हो—— Python base64 डीकोड आपका पहला पड़ाव है। बिल्ट-इन base64 module यह सब संभालता है, लेकिन bytes बनाम strings, URL-safe alphabets, और missing padding के बारे में छोटी-छोटी बातें लगभग हर developer को कम से कम एक बार फंसाती हैं—— मैंने code reviews में इस श्रेणी के errors को जितनी बार debug किया है उतना मानना नहीं चाहता। यह गाइड base64.b64decode(), urlsafe_b64decode(), automatic padding repair, files और HTTP responses से decoding, CLI tools, input validation, और before/after fixes के साथ चार सामान्य गलतियों को कवर करती है—— सभी Python 3.8+ के चलने योग्य examples हैं। अगर आपको बिना code लिखे एक quick one-off decode चाहिए, ToolDeck का Base64 डीकोडर browser में standard और URL-safe Base64 दोनों को तुरंत handle करता है।

  • base64.b64decode(s) Python stdlib में बिल्ट-इन है — कोई इंस्टॉलेशन नहीं चाहिए; यह हमेशा str नहीं, bytes लौटाता है।
  • bytes को Python string में बदलने के लिए b64decode() के बाद .decode("utf-8") चेन करें — यह फ़ंक्शन मूल टेक्स्ट एन्कोडिंग नहीं जानता।
  • URL-safe Base64 के लिए (+ और / के बजाय - और _ का उपयोग), base64.urlsafe_b64decode() का उपयोग करें — JWT, OAuth टोकन और Google API credentials में यही मानक है।
  • सामान्य "Incorrect padding" error को इससे ठीक करें: padded = s + "=" * (-len(s) % 4) — जरूरत के अनुसार 0, 1, या 2 अक्षर जोड़ता है।
  • बाहरी स्रोतों से किसी भी input पर validate=True सेट करें ताकि non-Base64 characters को चुपचाप skip करने की बजाय binascii.Error raise हो।

Base64 डीकोडिंग क्या है?

Base64 एक encoding scheme है जो arbitrary binary data को 64 printable ASCII characters की string के रूप में represent करता है: A–Z, a–z, 0–9, +, और /, और padding के लिए = का उपयोग करता है। हर 4 Base64 characters exactly 3 original bytes encode करते हैं, इसलिए encoded form source से लगभग 33% बड़ी होती है। Decoding इस प्रक्रिया को उल्टा करता है——ASCII representation को वापस original bytes में बदलता है।

Base64 data को encrypt नहीं करता। यह purely binary-to-text encoding है—— encoded string को कोई भी decoder से run करके पूरी तरह पढ़ सकता है:

पहले — Base64 encoded

eyJob3N0IjogImRiLXByb2QubXljb21wYW55LmludGVybmFsIiwgInBvcnQiOiA1NDMyLCAidXNlciI6ICJhcHBfc3ZjIn0=

बाद में — decoded

{"host": "db-prod.mycompany.internal", "port": 5432, "user": "app_svc"}

base64.b64decode() — Standard Library Decoding

Python का base64 module standard library के साथ आता है——zero installation, हमेशा उपलब्ध। Primary function है base64.b64decode(s, altchars=None, validate=False)। यह str, bytes, या bytearray accept करता है, और हमेशा bytes return करता है।

न्यूनतम कार्यशील उदाहरण

Python 3.8+
import base64
import json

# Encoded database config received from a secrets manager
encoded_config = (
    "eyJob3N0IjogImRiLXByb2QubXljb21wYW55LmludGVybmFsIiwgInBvcnQiOiA1NDMyLCAid"
    "XNlciI6ICJhcHBfc3ZjIiwgInBhc3N3b3JkIjogInM0ZmVQYXNzITIwMjYifQ=="
)

# Step 1: decode Base64 bytes
raw_bytes = base64.b64decode(encoded_config)
print(raw_bytes)
# b'{"host": "db-prod.mycompany.internal", "port": 5432, "user": "app_svc", "password": "s4fePass!2026"}'

# Step 2: convert bytes → str
config_str = raw_bytes.decode("utf-8")

# Step 3: parse into a dict
config = json.loads(config_str)
print(config["host"])    # db-prod.mycompany.internal
print(config["port"])    # 5432
नोट:b64decode() हमेशा bytes return करता है——string नहीं। अगर original data text था, तो .decode("utf-8") chain करें। अगर binary था (image, PDF, gzip archive), तो bytes को as-is रखें और file में लिखें या consuming library को directly pass करें।

विस्तृत उदाहरण: sort_keys, ensure_ascii, और strict validation

Python 3.8+
import base64
import binascii

# Token from an internal event bus — validate strictly (external input)
encoded_event = (
    "eyJldmVudCI6ICJvcmRlci5zaGlwcGVkIiwgIm9yZGVyX2lkIjogIk9SRC04ODQ3MiIsICJ"
    "0aW1lc3RhbXAiOiAiMjAyNi0wMy0xM1QxNDozMDowMFoiLCAicmVnaW9uIjogImV1LXdlc3QtMSJ9"
)

try:
    # validate=True raises binascii.Error on any non-Base64 character
    raw = base64.b64decode(encoded_event, validate=True)
    event = raw.decode("utf-8")
    print(event)
    # {"event": "order.shipped", "order_id": "ORD-88472", "timestamp": "2026-03-13T14:30:00Z", "region": "eu-west-1"}

except binascii.Error as exc:
    print(f"Invalid Base64: {exc}")
except UnicodeDecodeError as exc:
    print(f"Not UTF-8 text: {exc}")

URL-safe Base64 (base64url) डीकोडिंग

Standard Base64 + और /का उपयोग करता है, जो URLs में reserved characters हैं। URL-safe variant (RFC 4648 §5, जिसे “base64url” भी कहते हैं) इन्हें - और _ से replace करता है। यही encoding JWT tokens, OAuth 2.0 PKCE challenges, Google Cloud credentials, और अधिकांश आधुनिक web authentication flows में उपयोग होती है।

URL-safe Base64 को alphabet adjust किए बिना b64decode() में pass करने से data silently corrupt होगा या binascii.Error raise होगा। इसके बजाय base64.urlsafe_b64decode() का उपयोग करें——यह -+और _/ substitution automatically handle करता है।

Python 3.8+
import base64
import json

# JWT payload segment (the middle part between the two dots)
# JWTs use URL-safe Base64 without trailing "=" padding
jwt_payload_b64 = (
    "eyJ1c2VyX2lkIjogMjg5MywgInJvbGUiOiAiYWRtaW4iLCAiaXNzIjogImF1dGgubXljb21w"
    "YW55LmNvbSIsICJleHAiOiAxNzQwOTAwMDAwLCAianRpIjogImFiYzEyMzQ1LXh5ei05ODc2In0"
)

# Restore padding before decoding (JWT deliberately omits '=')
padded = jwt_payload_b64 + "=" * (-len(jwt_payload_b64) % 4)

payload_bytes = base64.urlsafe_b64decode(padded)
payload = json.loads(payload_bytes.decode("utf-8"))

print(payload["role"])    # admin
print(payload["iss"])     # auth.mycompany.com
print(payload["user_id"]) # 2893
नोट:Expression "=" * (-len(s) % 4) जरूरत के अनुसार exactly 0, 1, या 2 padding characters जोड़ता है और जब string पहले से correctly padded हो तो यह no-op है। यह JWT और OAuth padding issues के लिए idiomatic Python fix है।

base64.b64decode() Parameters Reference

नीचे दिए सभी parameters b64decode() और urlsafe_b64decode() दोनों पर apply होते हैं, सिवाय altchars के जो केवल b64decode() पर उपलब्ध है।

ParameterTypeDefaultविवरण
sbytes | str | bytearrayDecode करने के लिए Base64-encoded input; bytes types के साथ ASCII str भी accepted है।
altcharsbytes | NoneNone+ और / को replace करने वाला 2-byte sequence; standard URL-safe variant से परे custom Base64 alphabets enable करता है।
validateboolFalseजब True हो, Base64 alphabet के बाहर किसी भी character पर binascii.Error raise करता है; जब False हो, non-alphabet bytes (newlines, spaces) silently ignore होते हैं।

validate=False default PEM-formatted data और multi-line Base64 (जहाँ newlines आम हैं) के लिए जानबूझकर है। API payloads, user uploads, या किसी भी untrusted input के लिए, corrupt या injected data को जल्दी पकड़ने और clear error surface करने के लिएvalidate=True pass करें।

Python Base64 Decode Padding Error — कैसे ठीक करें

Python में Base64 decode करते समय सबसे बार आने वाली error है:

Python 3.8+
import base64

base64.b64decode("eyJ0eXBlIjogImFjY2VzcyJ9")
# binascii.Error: Incorrect padding

Base64 के लिए string lengths का 4 का multiple होना जरूरी है। जब data URLs, HTTP headers, या JWT libraries से गुजरता है, तो trailing =padding bytes बचाने के लिए strip हो जाती है। इसे ठीक करने के दो reliable तरीके हैं।

Option 1: Padding inline restore करें (recommended)

Python 3.8+
import base64
import json

def b64decode_unpadded(data: str | bytes) -> bytes:
    """Decode Base64 with automatic padding correction."""
    if isinstance(data, str):
        data = data.encode("ascii")
    data += b"=" * (-len(data) % 4)
    return base64.b64decode(data)

# Works regardless of how many '=' were stripped
token_a = "eyJ0eXBlIjogImFjY2VzcyJ9"       # 0 chars of padding stripped
token_b = "eyJ0eXBlIjogInJlZnJlc2gifQ"      # 1 char stripped
token_c = "eyJ0eXBlIjogImFwaV9rZXkifQ=="    # already padded

for token in (token_a, token_b, token_c):
    result = json.loads(b64decode_unpadded(token).decode("utf-8"))
    print(result["type"])
# access
# refresh
# api_key

Option 2: OAuth / JWT के लिए URL-safe decode with padding

Python 3.8+
import base64
import json

def decode_jwt_segment(segment: str) -> dict:
    """Decode a single JWT segment (header or payload)."""
    # Add padding, use URL-safe alphabet
    padded = segment + "=" * (-len(segment) % 4)
    raw = base64.urlsafe_b64decode(padded)
    return json.loads(raw.decode("utf-8"))

# Google OAuth ID token payload (simplified)
id_token_payload = (
    "eyJzdWIiOiAiMTEwNTY5NDkxMjM0NTY3ODkwMTIiLCAiZW1haWwiOiAic2FyYS5jaGVuQGV4"
    "YW1wbGUuY29tIiwgImhkIjogImV4YW1wbGUuY29tIiwgImlhdCI6IDE3NDA5MDAwMDB9"
)

claims = decode_jwt_segment(id_token_payload)
print(claims["email"])   # sara.chen@example.com
print(claims["hd"])      # example.com

File और API Response से Base64 Decode करना

Disk से Base64 पढ़ना और API payloads decode करना दो सबसे सामान्य production scenarios हैं। दोनों में proper error handling जरूरी है——corrupt padding और unexpected binary types वास्तविक घटनाएँ हैं, theoretical edge cases नहीं।

Base64 file पढ़ना और decode करना

Python 3.8+
import base64
import json
from pathlib import Path

def decode_attachment(envelope_path: str, output_path: str) -> None:
    """
    Read a JSON envelope with a Base64-encoded attachment,
    decode it, and write the binary output to disk.
    """
    try:
        envelope = json.loads(Path(envelope_path).read_text(encoding="utf-8"))
        encoded_data = envelope["attachment"]["data"]
        file_bytes = base64.b64decode(encoded_data, validate=True)
        Path(output_path).write_bytes(file_bytes)
        print(f"Saved {len(file_bytes):,} bytes → {output_path}")
    except FileNotFoundError:
        print(f"Envelope file not found: {envelope_path}")
    except (KeyError, TypeError):
        print("Unexpected envelope structure — 'attachment.data' missing")
    except base64.binascii.Error as exc:
        print(f"Invalid Base64 content: {exc}")

# Example envelope:
# {"attachment": {"filename": "invoice_2026_03.pdf", "data": "JVBERi0xLjQK..."}}
decode_attachment("order_ORD-88472.json", "invoice_2026_03.pdf")

HTTP API response से Base64 decode करना

Python 3.8+
import base64
import json
import urllib.request

def fetch_and_decode_secret(vault_url: str, secret_name: str) -> str:
    """
    Retrieve a Base64-encoded secret from an internal vault API
    and return the decoded plaintext value.
    """
    url = f"{vault_url}/v1/secrets/{secret_name}"
    req = urllib.request.Request(url, headers={"X-Vault-Token": "s.internal"})

    try:
        with urllib.request.urlopen(req, timeout=5) as resp:
            body = json.loads(resp.read().decode("utf-8"))
            # Vault returns: {"data": {"value": "<base64>", "encoding": "base64"}}
            encoded = body["data"]["value"]
            return base64.b64decode(encoded).decode("utf-8")

    except urllib.error.URLError as exc:
        raise RuntimeError(f"Vault unreachable: {exc}") from exc
    except (KeyError, UnicodeDecodeError, base64.binascii.Error) as exc:
        raise ValueError(f"Unexpected secret format: {exc}") from exc

# db_pass = fetch_and_decode_secret("https://vault.internal", "db-prod-password")
# print(db_pass)  # s4feP@ss!2026
नोट:अगर आप requests library use करते हैं, तो urllib.request को resp = requests.get(url, timeout=5, headers=headers) और body = resp.json() से replace करें। Base64 decoding logic identical है।

Command-Line Base64 डीकोडिंग

Quick terminal inspection के लिए——token verify करना, encoded config blob देखना, या API output को decoder से pipe करना——base64 command Linux और macOS पर available है। Python का built-in -m base64 module cross-platform काम करता है, Windows पर भी।

Bash
# Decode a Base64 string and print the result (Linux / macOS)
echo "eyJob3N0IjogImRiLXByb2QubXljb21wYW55LmludGVybmFsIn0=" | base64 --decode
# {"host": "db-prod.mycompany.internal"}

# Decode a file, save decoded output
base64 --decode encoded_payload.txt > decoded_output.json

# Python's cross-platform CLI decoder (works on Windows too)
python3 -m base64 -d encoded_payload.txt

# Decode a JWT payload segment inline — strip header/signature first
echo "eyJ1c2VyX2lkIjogMjg5MywgInJvbGUiOiAiYWRtaW4ifQ" | python3 -c "
import sys, base64, json
s = sys.stdin.read().strip()
padded = s + '=' * (-len(s) % 4)
print(json.dumps(json.loads(base64.urlsafe_b64decode(padded)), indent=2))
"

जहाँ shell pipeline लिखना overkill लगे, उन exploratory कामों के लिए, online Base64 Decoder में string paste करें—— यह URL-safe input auto-detect करता है और fly पर padding fix करता है।

Decode से पहले Base64 Input को Validate करना

जब Base64 data user input, webhook, या untrusted third-party API से आए, तो business logic के अंदर confusing binascii.Error tracebacks की बजाय clean, actionable errors surface करने के लिए decode से पहले validate करें। Python दो approaches देता है: exceptions catch करें, या regex से pre-validate करें।

Python 3.8+
import base64
import binascii
import re

# ── Option A: try/except (recommended for most code paths) ──────────────────

def safe_b64decode(data: str) -> bytes | None:
    """Return decoded bytes, or None if the input is not valid Base64."""
    try:
        padded = data + "=" * (-len(data) % 4)
        return base64.b64decode(padded, validate=True)
    except (binascii.Error, ValueError):
        return None

print(safe_b64decode("not-base64!!"))                     # None
print(safe_b64decode("eyJ0eXBlIjogInJlZnJlc2gifQ"))      # b'{"type": "refresh"}'


# ── Option B: regex pre-validation ──────────────────────────────────────────

# Standard Base64 (alphabet: A-Z a-z 0-9 + /)
_STANDARD_RE = re.compile(r"^[A-Za-z0-9+/]*={0,2}$")

# URL-safe Base64 (alphabet: A-Z a-z 0-9 - _)
_URLSAFE_RE = re.compile(r"^[A-Za-z0-9-_]*={0,2}$")

def is_valid_base64(s: str) -> bool:
    """True if s is a syntactically valid standard Base64 string."""
    # Length must be a multiple of 4 for fully padded strings
    stripped = s.rstrip("=")
    padded = stripped + "=" * (-len(stripped) % 4)
    return bool(_STANDARD_RE.match(padded))

print(is_valid_base64("SGVsbG8gV29ybGQ="))   # True
print(is_valid_base64("SGVsbG8gV29ybGQ!"))   # False  (! is not Base64)

High-Performance Alternative: pybase64

अधिकांश use cases के लिए, Python का stdlib base64 module पूरी तरह adequate है। अगर आप प्रति second हजारों API payloads process कर रहे हैं, tight loop में multi-megabyte binary attachments decode कर रहे हैं, या आपका profiler Base64 operations को hotspot दिखा रहा है——pybase64 consider करें। यह libbase64 के आसपास एक C-extension wrapper है और large inputs पर typically stdlib implementation से 2–5× faster है।

Bash
pip install pybase64
Python 3.8+
import pybase64

# Drop-in replacement — identical API to the stdlib base64 module
encoded_image = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQI12NgAAIABQ..."

image_bytes = pybase64.b64decode(encoded_image, validate=False)
print(f"Decoded {len(image_bytes):,} bytes")

# URL-safe variant — same as base64.urlsafe_b64decode()
token_bytes = pybase64.urlsafe_b64decode("eyJpZCI6IDQ3MX0=")
print(token_bytes)  # b'{"id": 471}'

# Benchmark note: on strings under ~10 KB the function-call overhead dominates
# and the speedup is negligible. Profile before switching.

API जानबूझकर base64 के identical है——import swap करें और कुछ नहीं बदलता। इसे केवल तब use करें जब profiling confirm करे कि Base64 actually bottleneck है, जो high-throughput data pipelines के बाहर uncommon है।

सामान्य गलतियाँ

मैंने code reviews में इन चारों errors को बार-बार देखा है——ये JavaScript या PHP जैसी भाषाओं से आने वाले developers में खासकर आम हैं जहाँ Base64 decode directly string return करता है, या ऐसे tutorials से जो error handling को पूरी तरह skip करते हैं।

गलती 1: Result पर .decode() call करना भूल जाना

Before · Python
After · Python
# ❌ b64decode() returns bytes — this crashes downstream
import base64

raw = base64.b64decode("eyJ1c2VyX2lkIjogNDcxLCAicm9sZSI6ICJhZG1pbiJ9")

# TypeError: byte indices must be integers or slices, not str
user_id = raw["user_id"]
# ✅ decode bytes → str, then parse
import base64, json

raw = base64.b64decode("eyJ1c2VyX2lkIjogNDcxLCAicm9sZSI6ICJhZG1pbiJ9")
payload = json.loads(raw.decode("utf-8"))
print(payload["user_id"])  # 471
print(payload["role"])     # admin

गलती 2: URL-safe Base64 input पर b64decode() use करना

Before · Python
After · Python
# ❌ JWT and OAuth tokens use '-' and '_' — not in standard alphabet
import base64

jwt_segment = "eyJ1c2VyX2lkIjogMjg5M30"
# binascii.Error or silently wrong bytes — unpredictable behaviour
base64.b64decode(jwt_segment)
# ✅ use urlsafe_b64decode() for any token with '-' or '_'
import base64, json

jwt_segment = "eyJ1c2VyX2lkIjogMjg5M30"
padded = jwt_segment + "=" * (-len(jwt_segment) % 4)
data = base64.urlsafe_b64decode(padded)
print(json.loads(data.decode("utf-8")))
# {'user_id': 2893}

गलती 3: Stripped tokens पर padding fix न करना

Before · Python
After · Python
# ❌ JWTs and most URL-transmitted tokens strip '=' — this crashes
import base64

# Valid JWT payload segment — no padding, as per spec
segment = "eyJ0eXBlIjogImFjY2VzcyIsICJqdGkiOiAiMzgxIn0"
base64.urlsafe_b64decode(segment)
# binascii.Error: Incorrect padding
# ✅ add padding before every urlsafe_b64decode() call
import base64, json

segment = "eyJ0eXBlIjogImFjY2VzcyIsICJqdGkiOiAiMzgxIn0"
padded = segment + "=" * (-len(segment) % 4)
result = json.loads(base64.urlsafe_b64decode(padded).decode("utf-8"))
print(result["type"])  # access
print(result["jti"])   # 381

गलती 4: Binary data पर .decode("utf-8") call करना

Before · Python
After · Python
# ❌ Binary files (PDF, PNG, ZIP) are not UTF-8 text — this crashes
import base64

# Base64-encoded PDF starts with JVBERi... (%PDF-)
pdf_b64 = "JVBERi0xLjQKJeLjz9MKNyAwIG9iago8PC9U..."
pdf_text = base64.b64decode(pdf_b64).decode("utf-8")
# UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2
# ✅ write binary directly to a file — no .decode() needed
import base64
from pathlib import Path

pdf_b64 = "JVBERi0xLjQKJeLjz9MKNyAwIG9iago8PC9U..."
pdf_bytes = base64.b64decode(pdf_b64)
Path("report_q1_2026.pdf").write_bytes(pdf_bytes)
print(f"Saved {len(pdf_bytes):,} bytes")

Python में बड़े Base64 Files Decode करना

200 MB Base64 file को Path.read_text() से load करके एक call में decode करने से encoded string, decoded bytes, और कोई भी intermediate representations simultaneously allocate होंगी—— constrained servers या Lambda functions पर memory easily exhaust हो सकती है। ~50–100 MB से बड़ी files के लिए, chunked approach use करें।

Disk पर Chunked decoding (full-file RAM load नहीं)

Python 3.8+
import base64

def decode_large_b64_file(input_path: str, output_path: str, chunk_size: int = 65536) -> None:
    """
    Decode a large Base64 file in chunks to avoid loading the entire encoded
    string into memory. chunk_size must be a multiple of 4 to keep Base64
    block boundaries aligned across reads.
    """
    assert chunk_size % 4 == 0, "chunk_size must be a multiple of 4"

    bytes_written = 0
    with open(input_path, "rb") as src, open(output_path, "wb") as dst:
        while True:
            chunk = src.read(chunk_size)
            if not chunk:
                break
            # Strip whitespace that may appear in wrapped/multiline Base64
            chunk = chunk.strip()
            if chunk:
                dst.write(base64.b64decode(chunk))
                bytes_written += len(chunk)

    print(f"Decoded {bytes_written:,} Base64 bytes → {output_path}")

# Example: decode a 300 MB database snapshot stored as Base64
decode_large_b64_file("snapshot_2026_03_13.b64", "snapshot_2026_03_13.sql.gz")

PEM / multiline data के लिए base64.decodebytes() से Decoding

Python 3.8+
import base64

# base64.decodebytes() is designed for MIME / PEM Base64 that wraps at 76 chars.
# It silently ignores whitespace and newlines — perfect for certificate files.

with open("server_cert.pem", "rb") as f:
    pem_data = f.read()

# Strip PEM headers if present, then decode
lines = [
    line for line in pem_data.splitlines()
    if not line.startswith(b"-----")
]
raw_cert = base64.decodebytes(b"
".join(lines))
print(f"Certificate DER payload: {len(raw_cert):,} bytes")
नोट:PEM certificates, MIME attachments, और किसी भी fixed line widths पर wrap होने वाले Base64 के लिए base64.decodebytes() use करें। बड़े opaque blobs (backups, media files) के लिए ऊपर दिए chunked approach का उपयोग करें। Compact, single-line tokens (JWT, OAuth) के लिए, b64decode() या urlsafe_b64decode() हमेशा सही choice है।

Python Base64 Decoding Methods — Quick Comparison

MethodAlphabetPaddingOutputInstall जरूरीसबसे उपयुक्त
base64.b64decode()Standard (A–Z a–z 0–9 +/)जरूरीbytesनहीं (stdlib)General-purpose, email, PEM
base64.decodebytes()Standard (A–Z a–z 0–9 +/)Ignored (whitespace strip)bytesनहीं (stdlib)PEM certs, MIME attachments, multiline Base64
base64.urlsafe_b64decode()URL-safe (A–Z a–z 0–9 -_)जरूरीbytesनहीं (stdlib)JWT, OAuth, Google Cloud APIs
base64.b32decode()32-char (A–Z, 2–7)जरूरीbytesनहीं (stdlib)TOTP secrets, DNS-safe IDs
base64.b16decode()Hex (0–9, A–F)कोई नहींbytesनहीं (stdlib)Hex-encoded checksums, hashes
pybase64.b64decode()Standard (A–Z a–z 0–9 +/)जरूरीbytesहाँ (pip)High-throughput pipelines, large payloads
CLI: base64 --decodeStandardAutostdoutनहीं (system)Quick terminal inspection

Default के रूप में b64decode() use करें। जैसे ही input में - या _ दिखे,urlsafe_b64decode() पर switch करें——ये characters URL-safe Base64 का unmistakable sign हैं।pybase64 तभी लें जब profiling bottleneck confirm करे। Development के दौरान one-off checks के लिए, ToolDeck का Base64 डीकोडरदोनों alphabets handle करता है और padding auto-repair करता है——Python environment की जरूरत नहीं।

अक्सर पूछे जाने वाले प्रश्न

Python में Base64 string को regular string में कैसे decode करें?

bytes पाने के लिए base64.b64decode(encoded) call करें, फिर Python strपाने के लिए result पर .decode("utf-8") call करें। दो steps हमेशा अलग होते हैं क्योंकि b64decode() केवल Base64 alphabet reverse करता है——यह नहीं जानता कि original content UTF-8, Latin-1, या binary था। अगर data non-UTF-8 encoding use करता है, तो .decode() को correct codec name pass करें, उदाहरण के लिए .decode("latin-1")

Python में Base64 decode करते समय "Incorrect padding" क्यों आती है?

Base64 strings का 4 characters का multiple लंबी होना जरूरी है। JWTs, OAuth tokens, और URLs में transmit किए गए data से trailing = padding अक्सर strip हो जाती है। Decode से पहले "=" * (-len(s) % 4) append करके fix करें। यह formula जरूरत के अनुसार exactly 0, 1, या 2 characters add करता है, और जब string पहले से correctly padded हो तो safe no-op है।

Python में b64decode() और urlsafe_b64decode() में क्या अंतर है?

दोनों same Base64 algorithm decode करते हैं लेकिन 62nd और 63rd characters के लिए different alphabets use करते हैं। b64decode() + और / use करता है; urlsafe_b64decode() - और _ use करता है। URL-safe variant RFC 4648 §5 में defined है और वहाँ use होता है जहाँ Base64 को URLs, HTTP headers, या cookie values में बिना percent-encoding के survive करना हो। इन्हें mix up करने से binascii.Error या silently corrupt output मिलता है।

Python में Base64-encoded image को कैसे decode करें?

base64.b64decode(encoded) से bytes में decode करें, फिर वे bytes directly file में write करें——image data पर .decode("utf-8") call करें। अगर input एक data URL है (जैसे data:image/png;base64,iVBORw0KGgo…), पहले prefix strip करें:

Python 3.8+
import base64
from pathlib import Path

# Data URL from an <img src="..."> or an API response
data_url = (
    "data:image/png;base64,"
    "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQI12NgAAIABQ=="
)

# Split off the "data:image/png;base64," prefix
_, encoded = data_url.split(",", 1)
image_bytes = base64.b64decode(encoded)
Path("avatar_jsmith.png").write_bytes(image_bytes)
print(f"Saved {len(image_bytes)} bytes")

क्या Python में कोई module import किए बिना Base64 decode किया जा सकता है?

Technically हाँ, लेकिन कोई कारण नहीं है। base64 module Python के standard library का हिस्सा है, हमेशा available, हमेशा installed——इसकी कोई dependencies नहीं हैं और इसके functions C में implemented हैं। Base64 को scratch से reimplement करना slower, more error-prone, और harder to maintain होगा। हमेशा import base64 use करें।

Python में Base64 decode कैसे करें जब input string नहीं, bytes हो?

base64.b64decode() str, bytes, और bytearray interchangeably accept करता है——कोई conversion जरूरी नहीं। अगर आपको socket या file read से b"SGVsbG8=" मिले, directly pass करें। Padding repair bytes mode में same तरीके से काम करता है: data + b"=" * (-len(data) % 4) bytes mode में।

संबंधित उपकरण

  • Base64 Encode — text या binary files को तुरंत Base64 में encode करें; script run किए बिना Python decoding code के लिए test fixtures generate करने में useful।
  • JWT Decoder — code लिखे बिना JWT header और payload inspect करें; payload ऊपर दिखाए examples की तरह hood के नीचे URL-safe Base64 से decode होता है।
  • URL Decode — query strings और path segments को percent-decode करें; OAuth callback URLs या webhook payloads parse करते समय अक्सर Base64 decoding के साथ जरूरत होती है।
  • URL Encode — special characters को percent-encode करें; Base64-encoded value को URL query parameter के अंदर safely embed करने पर handy।
इसमें भी उपलब्ध:JavaScriptGoJavaC#
MS
Maria SantosBackend Developer

Maria is a backend developer specialising in Python and API integration. She has broad experience with data pipelines, serialisation formats, and building reliable server-side services. She is an active member of the Python community and enjoys writing practical, example-driven guides that help developers solve real problems without unnecessary theory.

DV
Dmitri Volkovतकनीकी समीक्षक

Dmitri is a DevOps engineer who relies on Python as his primary scripting and automation language. He builds internal tooling, CI/CD pipelines, and infrastructure automation scripts that run in production across distributed teams. He writes about the Python standard library, subprocess management, file processing, encoding utilities, and the practical shell-adjacent Python that DevOps engineers use every day.