TheAlgorithms/Python · error · ValueError

base64 encoded data should only contain ASCII characters

Error message

base64 encoded data should only contain ASCII characters

What it means

Raised by base64_decode() when encoded_data is a bytes object whose contents are not valid UTF-8/ASCII. The function decodes bytes to str before processing; non-ASCII bytes mean the input cannot be Base64 text (the charset is ASCII-only), so a ValueError is raised.

Source

Thrown at ciphers/base64_cipher.py:102

    Traceback (most recent call last):
      ...
    AssertionError: Incorrect padding
    """
    # Make sure encoded_data is either a string or a bytes-like object
    if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str):
        msg = (
            "argument should be a bytes-like object or ASCII string, "
            f"not '{encoded_data.__class__.__name__}'"
        )
        raise TypeError(msg)

    # In case encoded_data is a bytes-like object, make sure it contains only
    # ASCII characters so we convert it to a string object
    if isinstance(encoded_data, bytes):
        try:
            encoded_data = encoded_data.decode("utf-8")
        except UnicodeDecodeError:
            raise ValueError("base64 encoded data should only contain ASCII characters")

    padding = encoded_data.count("=")

    # Check if the encoded string contains non base64 characters
    if padding:
        assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (
            "Invalid base64 character(s) found."
        )
    else:
        assert all(char in B64_CHARSET for char in encoded_data), (
            "Invalid base64 character(s) found."
        )

    # Check the padding
    assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding"

    if padding:
        # Remove padding if there is one

View on GitHub (pinned to f5988cc097)

Solutions

  1. Verify the data is actually Base64 text before calling (ASCII-only, valid charset)
  2. If you have raw binary, do not call base64_decode on it — it is already decoded material
  3. Strip non-ASCII bytes or reject the payload upstream with a clear error

Example fix

# before
base64_decode(raw_socket_bytes)  # may contain non-ASCII

# after
try:
    text = raw_socket_bytes.decode("ascii")
except UnicodeDecodeError:
    raise ValueError("payload is not base64 text") from None
base64_decode(text)
Defensive patterns

Strategy: validation

Validate before calling

if isinstance(encoded_data, bytes):
    encoded_data.decode("ascii")  # raises UnicodeDecodeError early if not ASCII text

Type guard

def is_ascii_text(data: bytes) -> bool:
    try:
        data.decode("ascii")
        return True
    except UnicodeDecodeError:
        return False

Try / catch

try:
    decoded = base64_decode(encoded_data)
except ValueError as exc:
    if "ASCII" in str(exc):
        raise ValueError("payload is not base64 text; got binary data") from None
    raise

Prevention

When it happens

Trigger: Calling base64_decode with raw binary (e.g. an encrypted blob, image bytes) instead of Base64 text; bytes containing values > 0x7F such as b'\xff\xfeabc'; double-decoding garbage from a network socket.

Common situations: Confusing 'binary data' with 'Base64-encoded data' in a pipeline; reading from a socket/file that returns arbitrary bytes; corrupted payloads after transport through a lossy channel.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/69551e2c29f3663b. Report an issue: GitHub.