77
88import re
99import struct
10+ import string
1011import binascii
1112
1213
@@ -52,7 +53,7 @@ def b64encode(s, altchars=None):
5253 # Strip off the trailing newline
5354 encoded = binascii .b2a_base64 (s )[:- 1 ]
5455 if altchars is not None :
55- return _translate ( encoded , { '+' : altchars [ 0 ], '/' : altchars [1 ]} )
56+ return encoded . translate ( string . maketrans ( b'+/' , altchars [: 2 ]) )
5657 return encoded
5758
5859
@@ -68,7 +69,7 @@ def b64decode(s, altchars=None):
6869 string.
6970 """
7071 if altchars is not None :
71- s = _translate ( s , { altchars [0 ]: '+' , altchars [ 1 ]: '/' } )
72+ s = s . translate ( string . maketrans ( altchars [: 2 ], '+/' ) )
7273 try :
7374 return binascii .a2b_base64 (s )
7475 except binascii .Error , msg :
@@ -92,13 +93,16 @@ def standard_b64decode(s):
9293 """
9394 return b64decode (s )
9495
96+ _urlsafe_encode_translation = string .maketrans (b'+/' , b'-_' )
97+ _urlsafe_decode_translation = string .maketrans (b'-_' , b'+/' )
98+
9599def urlsafe_b64encode (s ):
96100 """Encode a string using a url-safe Base64 alphabet.
97101
98102 s is the string to encode. The encoded string is returned. The alphabet
99103 uses '-' instead of '+' and '_' instead of '/'.
100104 """
101- return b64encode (s , '-_' )
105+ return b64encode (s ). translate ( _urlsafe_encode_translation )
102106
103107def urlsafe_b64decode (s ):
104108 """Decode a string encoded with the standard Base64 alphabet.
@@ -109,7 +113,7 @@ def urlsafe_b64decode(s):
109113
110114 The alphabet uses '-' instead of '+' and '_' instead of '/'.
111115 """
112- return b64decode (s , '-_' )
116+ return b64decode (s . translate ( _urlsafe_decode_translation ) )
113117
114118
115119
@@ -200,7 +204,7 @@ def b32decode(s, casefold=False, map01=None):
200204 # False, or the character to map the digit 1 (one) to. It should be
201205 # either L (el) or I (eye).
202206 if map01 :
203- s = _translate ( s , { '0' : 'O' , '1' : map01 } )
207+ s = s . translate ( string . maketrans ( b'01' , b 'O' + map01 ) )
204208 if casefold :
205209 s = s .upper ()
206210 # Strip off pad characters from the right. We need to count the pad
0 commit comments