{"record":{"id":"69551e2c29f3663b","repo":"TheAlgorithms/Python","slug":"base64-encoded-data-should-only-contain-ascii-char","errorCode":null,"errorMessage":"base64 encoded data should only contain ASCII characters","messagePattern":"base64 encoded data should only contain ASCII characters","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"ciphers/base64_cipher.py","lineNumber":102,"sourceCode":"    Traceback (most recent call last):\n      ...\n    AssertionError: Incorrect padding\n    \"\"\"\n    # Make sure encoded_data is either a string or a bytes-like object\n    if not isinstance(encoded_data, bytes) and not isinstance(encoded_data, str):\n        msg = (\n            \"argument should be a bytes-like object or ASCII string, \"\n            f\"not '{encoded_data.__class__.__name__}'\"\n        )\n        raise TypeError(msg)\n\n    # In case encoded_data is a bytes-like object, make sure it contains only\n    # ASCII characters so we convert it to a string object\n    if isinstance(encoded_data, bytes):\n        try:\n            encoded_data = encoded_data.decode(\"utf-8\")\n        except UnicodeDecodeError:\n            raise ValueError(\"base64 encoded data should only contain ASCII characters\")\n\n    padding = encoded_data.count(\"=\")\n\n    # Check if the encoded string contains non base64 characters\n    if padding:\n        assert all(char in B64_CHARSET for char in encoded_data[:-padding]), (\n            \"Invalid base64 character(s) found.\"\n        )\n    else:\n        assert all(char in B64_CHARSET for char in encoded_data), (\n            \"Invalid base64 character(s) found.\"\n        )\n\n    # Check the padding\n    assert len(encoded_data) % 4 == 0 and padding < 3, \"Incorrect padding\"\n\n    if padding:\n        # Remove padding if there is one","sourceCodeStart":84,"sourceCodeEnd":120,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/ciphers/base64_cipher.py#L84-L120","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Verify the data is actually Base64 text before calling (ASCII-only, valid charset)","If you have raw binary, do not call base64_decode on it — it is already decoded material","Strip non-ASCII bytes or reject the payload upstream with a clear error"],"exampleFix":"# before\nbase64_decode(raw_socket_bytes)  # may contain non-ASCII\n\n# after\ntry:\n    text = raw_socket_bytes.decode(\"ascii\")\nexcept UnicodeDecodeError:\n    raise ValueError(\"payload is not base64 text\") from None\nbase64_decode(text)","handlingStrategy":"validation","validationCode":"if isinstance(encoded_data, bytes):\n    encoded_data.decode(\"ascii\")  # raises UnicodeDecodeError early if not ASCII text","typeGuard":"def is_ascii_text(data: bytes) -> bool:\n    try:\n        data.decode(\"ascii\")\n        return True\n    except UnicodeDecodeError:\n        return False","tryCatchPattern":"try:\n    decoded = base64_decode(encoded_data)\nexcept ValueError as exc:\n    if \"ASCII\" in str(exc):\n        raise ValueError(\"payload is not base64 text; got binary data\") from None\n    raise","preventionTips":["Distinguish encoded (ASCII text) from raw binary at your pipeline boundaries","Validate ASCII decodability before calling base64_decode on bytes","Reject corrupted/non-ASCII payloads upstream with explicit errors"],"tags":["base64","decoding","unicode","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}