(encoded)
| 98 | # |
| 99 | |
| 100 | def decode_b(encoded): |
| 101 | # First try encoding with validate=True, fixing the padding if needed. |
| 102 | # This will succeed only if encoded includes no invalid characters. |
| 103 | pad_err = len(encoded) % 4 |
| 104 | missing_padding = b'==='[:4-pad_err] if pad_err else b'' |
| 105 | try: |
| 106 | return ( |
| 107 | base64.b64decode(encoded + missing_padding, validate=True), |
| 108 | [errors.InvalidBase64PaddingDefect()] if pad_err else [], |
| 109 | ) |
| 110 | except binascii.Error: |
| 111 | # Since we had correct padding, this is likely an invalid char error. |
| 112 | # |
| 113 | # The non-alphabet characters are ignored as far as padding |
| 114 | # goes, but we don't know how many there are. So try without adding |
| 115 | # padding to see if it works. |
| 116 | try: |
| 117 | return ( |
| 118 | base64.b64decode(encoded, validate=False), |
| 119 | [errors.InvalidBase64CharactersDefect()], |
| 120 | ) |
| 121 | except binascii.Error: |
| 122 | # Add as much padding as could possibly be necessary (extra padding |
| 123 | # is ignored). |
| 124 | try: |
| 125 | return ( |
| 126 | base64.b64decode(encoded + b'==', validate=False), |
| 127 | [errors.InvalidBase64CharactersDefect(), |
| 128 | errors.InvalidBase64PaddingDefect()], |
| 129 | ) |
| 130 | except binascii.Error: |
| 131 | # This only happens when the encoded string's length is 1 more |
| 132 | # than a multiple of 4, which is invalid. |
| 133 | # |
| 134 | # bpo-27397: Just return the encoded string since there's no |
| 135 | # way to decode. |
| 136 | return encoded, [errors.InvalidBase64LengthDefect()] |
| 137 | |
| 138 | def encode_b(bstring): |
| 139 | return base64.b64encode(bstring).decode('ascii') |
no outgoing calls
no test coverage detected
searching dependent graphs…