py2 to 3 base64 issues
MRAB
python at mrabarnett.plus.com
Fri Aug 9 12:25:11 EDT 2019
On 2019-08-09 17:06, Larry Martell wrote:
> I have some python 2 code:
>
> def decode(key, string):
> decoded_chars = []
> string = base64.urlsafe_b64decode(string)
> for i in range(len(string)):
> key_c = key[i % len(key)]
> encoded_c = chr(abs(ord(string[i]) - ord(key_c) % 256))
> decoded_chars.append(encoded_c)
> decoded_string = "".join(decoded_chars)
> return decoded_string
>
> and if I call it like this in py2 it works as expected:
>
> s = 'V3NYVY95iImnnJWCmqphWFFzU1qvqsV6x83Mxa7HipZitZeMxbe709jJtbfW6Y6blQ=='
> key = '!@#$VERYsecRet)('
> decode(key, s)
>
> In py3 it fails with
>
> TypeError: ord() expected string of length 1, but int found
>
> I know that in py3 base64.urlsafe_b64decode is returning bytes not
> chars and that is what that is happening, and I thought the solution
> would be to decode it, but what codec would I use for this?
>
I'll use the b and u prefixes for clarity.
In Python 2, b'abc'[0] is b'a' and u'abc'[0] is u'a'.
In Python 3, b'abc'[0] is 65 and u'abc'[0] is u'a'.
Using ord on an int raises an exception.
More information about the Python-list
mailing list