Skip to content

Commit 715f313

Browse files
committed
Improve base64decode faster when running validate=True
This is done by compiling the regex that validates that the encoded data only has valid base64 characters.
1 parent b238545 commit 715f313

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

Lib/base64.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
'urlsafe_b64encode', 'urlsafe_b64decode',
2929
]
3030

31-
31+
VALID_BASE64_REGEX = re.compile(b'^[A-Za-z0-9+/]*={0,2}$')
3232
bytes_types = (bytes, bytearray) # Types acceptable as binary data
3333

3434
def _bytes_from_decode_data(s):
@@ -82,7 +82,7 @@ def b64decode(s, altchars=None, validate=False):
8282
altchars = _bytes_from_decode_data(altchars)
8383
assert len(altchars) == 2, repr(altchars)
8484
s = s.translate(bytes.maketrans(altchars, b'+/'))
85-
if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
85+
if validate and not VALID_BASE64_REGEX.match(s):
8686
raise binascii.Error('Non-base64 digit found')
8787
return binascii.a2b_base64(s)
8888

0 commit comments

Comments
 (0)