Skip to content

Commit 7e35081

Browse files
bpo-34736: improve error message for invalid length b64decode inputs (GH-9563)
Improvements: 1. Include the number of valid data characters in the error message. 2. Mention "number of data characters" rather than "length". https://bugs.python.org/issue34736 (cherry picked from commit 1fba2ff) Co-authored-by: Tal Einat <[email protected]>
1 parent 85ccedc commit 7e35081

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

Lib/test/test_binascii.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import unittest
44
import binascii
55
import array
6+
import re
67

78
# Note: "*_hex" functions are aliases for "(un)hexlify"
89
b2a_functions = ['b2a_base64', 'b2a_hex', 'b2a_hqx', 'b2a_qp', 'b2a_uu',
@@ -127,7 +128,10 @@ def assertIncorrectPadding(data):
127128

128129
# Test base64 with invalid number of valid characters (1 mod 4)
129130
def assertInvalidLength(data):
130-
with self.assertRaisesRegex(binascii.Error, r'(?i)invalid.+length'):
131+
n_data_chars = len(re.sub(br'[^A-Za-z0-9/+]', br'', data))
132+
expected_errmsg_re = \
133+
r'(?i)Invalid.+number of data characters.+' + str(n_data_chars)
134+
with self.assertRaisesRegex(binascii.Error, expected_errmsg_re):
131135
binascii.a2b_base64(self.type2test(data))
132136

133137
assertInvalidLength(b'a')

Modules/binascii.c

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -438,6 +438,7 @@ binascii_a2b_base64_impl(PyObject *module, Py_buffer *data)
438438
{
439439
const unsigned char *ascii_data;
440440
unsigned char *bin_data;
441+
unsigned char *bin_data_start;
441442
int leftbits = 0;
442443
unsigned char this_ch;
443444
unsigned int leftchar = 0;
@@ -461,6 +462,7 @@ binascii_a2b_base64_impl(PyObject *module, Py_buffer *data)
461462
bin_data = _PyBytesWriter_Alloc(&writer, bin_len);
462463
if (bin_data == NULL)
463464
return NULL;
465+
bin_data_start = bin_data;
464466

465467
for( ; ascii_len > 0; ascii_len--, ascii_data++) {
466468
this_ch = *ascii_data;
@@ -516,9 +518,11 @@ binascii_a2b_base64_impl(PyObject *module, Py_buffer *data)
516518
** This is an invalid length, as there is no possible input that
517519
** could encoded into such a base64 string.
518520
*/
519-
PyErr_SetString(Error,
520-
"Invalid base64-encoded string: "
521-
"length cannot be 1 more than a multiple of 4");
521+
PyErr_Format(Error,
522+
"Invalid base64-encoded string: "
523+
"number of data characters (%d) cannot be 1 more "
524+
"than a multiple of 4",
525+
(bin_data - bin_data_start) / 3 * 4 + 1);
522526
} else {
523527
PyErr_SetString(Error, "Incorrect padding");
524528
}

0 commit comments

Comments
 (0)