Python Forum
how to encode and decode same value - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to encode and decode same value (/thread-29522.html)



how to encode and decode same value - absolut - Sep-07-2020

Hi.
I obtain these data:
ADhlamtsOXdreXE2eAA0VFpWTGJBWDdSZW83d3AwYnJnNlVnSEpRcTlvR0wwMTlldUhSelJ6bXRtTTRnbmUxU
I'm tring to decode and then encode to check that I have the same result but the second python program not gives the result of the first. I'll explain better with examples:


 $ more decode.py
import base64
code = "ADhlamtsOXdreXE2eAA0VFpWTGJBWDdSZW83d3AwYnJnNlVnSEpRcTlvR0wwMTlldUhSelJ6bXRtTTRnbmUxU
HpERklwdnFGTzN0eFVzNXgxZlN5"
result=base64.b64decode(code)
print result
# b'admin:202cb962ac59075b964b07152d234b70'
 $ more code.py
import base64
code = "8ejkl9wkyq6x4TZVLbAX7Reo7wp0brg6UgHJQq9oGL019euHRzRzmtmM4gne1PzDFIpvqFO3txUs5x1fSy"
result=base64.b64encode(code)
print result
# b'admin:202cb962ac59075b964b07152d234b70'
 $ python decode.py
8ejkl9wkyq6x4TZVLbAX7Reo7wp0brg6UgHJQq9oGL019euHRzRzmtmM4gne1PzDFIpvqFO3txUs5x1fSy
$ python code.py
OGVqa2w5d2t5cTZ4NFRaVkxiQVg3UmVvN3dwMGJyZzZVZ0hKUXE5b0dMMDE5ZXVIUnpSem10bU00Z25lMVB6REZJcHZxRk8zdHhVczV4MWZTeQ=
When I code I need obtain ADhlamtsOXdreXE2eAA0VFpWTGJBWDdSZW83d3AwYnJnNlVnSEpRcTlvR0wwMTlldUhSelJ6bXRtTTRnbmUxU


What am I doing wrong? Many thanks and sorry for my English!


RE: how to encode and decode same value - bowlofred - Sep-07-2020

When you decode (especially if you're decoding random data), the possible output string may include null bytes. If you're using python2 and print out the data, these null bytes will just disappear.

>>> print b'\x00abc\x00def'
abcdef
>>> b'\x00abc\x00def' == 'abcdef'
False
So the printed line is not the same as the data you printed. Taking the printed line and encoding will get you something else. This isn't a problem if you only encode ascii, but if you're decoding random data, this is likely to happen.

Don't assume the printed value of the string is equal to the string. Also, use python3 and this is harder to mess up.


RE: how to encode and decode same value - TomToad - Sep-08-2020

Might be better to first encode random data, then decode the result to see if you get the original data, instead of the other way around. base64 encrypted data will always be printable ASCII characters so you will not run into the problem with null bytes and unprintable characters.