Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Lib/test/test_binascii.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,34 @@ def addnoise(line):
# empty strings. TBD: shouldn't it raise an exception instead ?
self.assertEqual(binascii.a2b_base64(self.type2test(fillers)), b'')

def test_base64errors(self):
# Test base64 with invalid padding
def assertIncorrectPadding(data):
with self.assertRaisesRegex(binascii.Error, r'(?i)Incorrect padding'):
binascii.a2b_base64(self.type2test(data))

assertIncorrectPadding(b'ab')
assertIncorrectPadding(b'ab=')
assertIncorrectPadding(b'abc')
assertIncorrectPadding(b'abcdef')
assertIncorrectPadding(b'abcdef=')
assertIncorrectPadding(b'abcdefg')
assertIncorrectPadding(b'a=b=')
assertIncorrectPadding(b'a\nb=')

# Test base64 with invalid number of valid characters (1 mod 4)
def assertInvalidLength(data):
with self.assertRaisesRegex(binascii.Error, r'(?i)invalid.+length'):
binascii.a2b_base64(self.type2test(data))

assertInvalidLength(b'a')
assertInvalidLength(b'a=')
assertInvalidLength(b'a==')
assertInvalidLength(b'a===')
assertInvalidLength(b'a' * 5)
assertInvalidLength(b'a' * (4 * 87 + 1))
assertInvalidLength(b'A\tB\nC ??DE') # only 5 valid characters

def test_uu(self):
MAX_UU = 45
for backtick in (True, False):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
improve base64 exception message for encoded inputs of invalid length
13 changes: 12 additions & 1 deletion Modules/binascii.c
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,18 @@ binascii_a2b_base64_impl(PyObject *module, Py_buffer *data)
}

if (leftbits != 0) {
PyErr_SetString(Error, "Incorrect padding");
if (leftbits == 6) {
/*
** There is exactly one extra valid, non-padding, base64 character.
** This is an invalid length, as there is no possible input that
** could encoded into such a base64 string.
*/
PyErr_SetString(Error,
"Invalid base64-encoded string: "
"length cannot be 1 more than a multiple of 4");
} else {
PyErr_SetString(Error, "Incorrect padding");
}
_PyBytesWriter_Dealloc(&writer);
return NULL;
}
Expand Down