Skip to content

Unexpected nested exception with b64decode #129505

@hannob

Description

@hannob

Bug report

Bug description:

The b64decode function of the base64 standard library module can behave in unexpected ways with invalid inputs.

Take this example:

#!/usr/bin/python3
import base64
base64.b64decode('a\xd6==')

According to the docs, I would expect that invalid characters in the input cause a binascii.Error exception. However, this example gives me the following:

Traceback (most recent call last):
  File "/usr/lib/python3.12/base64.py", line 37, in _bytes_from_decode_data
    return s.encode('ascii')
           ^^^^^^^^^^^^^^^^^
UnicodeEncodeError: 'ascii' codec can't encode character '\xd6' in position 1: ordinal not in range(128)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/tmp/./test", line 3, in <module>
    base64.b64decode('a\xd6==')
  File "/usr/lib/python3.12/base64.py", line 83, in b64decode
    s = _bytes_from_decode_data(s)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/base64.py", line 39, in _bytes_from_decode_data
    raise ValueError('string argument should contain only ASCII characters')
ValueError: string argument should contain only ASCII characters

So not only do I get an exception that I don't expect according to the docs, it appears there is a bug in the internal exception handling causing an exception (ValueError) during another exception (UnicodeEncodeError).

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dirstdlibStandard Library Python modules in the Lib/ directory

    Projects

    Status

    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions