Skip to content

Commit ec5e3a5

Browse files
authored
gh-145968: Fix base64.b64decode altchars translation in specific cases (GH-145969)
When altchars overlaps with the standard ones, the translation does not always yield to the expected outcome.
1 parent 757e2ff commit ec5e3a5

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

Lib/base64.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,13 @@ def b64decode(s, altchars=None, validate=_NOT_SPECIFIED, *, ignorechars=_NOT_SPE
100100
break
101101
s = s.translate(bytes.maketrans(altchars, b'+/'))
102102
else:
103-
trans = bytes.maketrans(b'+/' + altchars, altchars + b'+/')
103+
trans_in = set(b'+/') - set(altchars)
104+
if len(trans_in) == 2:
105+
# we can't use the reqult of unordered sets here
106+
trans = bytes.maketrans(altchars + b'+/', b'+/' + altchars)
107+
else:
108+
trans = bytes.maketrans(altchars + bytes(trans_in),
109+
b'+/' + bytes(set(altchars) - set(b'+/')))
104110
s = s.translate(trans)
105111
ignorechars = ignorechars.translate(trans)
106112
if ignorechars is _NOT_SPECIFIED:

Lib/test/test_base64.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,13 @@ def test_b64decode_altchars(self):
293293
eq(base64.b64decode(data_str, altchars=altchars_str), res)
294294
eq(base64.b64decode(data, altchars=altchars, ignorechars=b'\n'), res)
295295

296+
eq(base64.b64decode(b'/----', altchars=b'-+', ignorechars=b'/'), b'\xfb\xef\xbe')
297+
eq(base64.b64decode(b'/----', altchars=b'+-', ignorechars=b'/'), b'\xff\xff\xff')
298+
eq(base64.b64decode(b'+----', altchars=b'-/', ignorechars=b'+'), b'\xfb\xef\xbe')
299+
eq(base64.b64decode(b'+----', altchars=b'/-', ignorechars=b'+'), b'\xff\xff\xff')
300+
eq(base64.b64decode(b'+/+/', altchars=b'/+', ignorechars=b''), b'\xff\xef\xfe')
301+
eq(base64.b64decode(b'/+/+', altchars=b'+/', ignorechars=b''), b'\xff\xef\xfe')
302+
296303
self.assertRaises(ValueError, base64.b64decode, b'', altchars=b'+')
297304
self.assertRaises(ValueError, base64.b64decode, b'', altchars=b'+/-')
298305
self.assertRaises(ValueError, base64.b64decode, '', altchars='+')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix translation in :func:`base64.b64decode` when altchars overlaps with the
2+
standard ones.

0 commit comments

Comments
 (0)