0

I am trying to make a hex string out of a base64 string. The original string is: M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc== It should become:

3344af61e4473d60d85481bf822a6d04 5a8131075639babc6ebd510ea59f3b5a ef932e915b41e21823100b59a1c9b633 15e494902e62c38eb83f99c26147 

My code is:

str1 = "M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc=="
d = base64.b64decode(str1)
d1 = d.decode('utf-8')
print(d1)

However, I get the message in decode utf-8:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xaf in position 2: invalid start byte

The output of d1 is:

b'3D\xafa\xe4G=`\xd8T\x81\xbf\x82*m\x04Z\x811\x07V9\xba\xbcn\xbdQ\x0e\xa5\x9f;Z\xef\x93.\x91[A\xe2\x18#\x10\x0bY\xa1\xc9\xb63\x15\xe4\x94\x90.b\xc3\x8e\xb8?\x99\xc2aG'

Where is my mistake? I would also like to see the backwards version from the hex string to base64. I use python 3.

JosefZ
  • 28,460
  • 5
  • 44
  • 83
Hemmelig
  • 803
  • 10
  • 22

1 Answers1

1

The result of base64.b64decode(str1) is:

  • a bytes object already in Python 3.
  • a str object in Python 2 (and str and bytes are synonyms here).

The following commented script covers both Python versions:

import base64
str1 = "M0SvYeRHPWDYVIG/giptBFqBMQdWObq8br1RDqWfO1rvky6RW0HiGCMQC1mhybYzFeSUkC5iw464P5nCYUc=="
d = base64.b64decode(str1)
print(type(d))
print(type(d) is bytes)

# python 2
if type(d) is str:
    d = bytearray(d)

# The old format style was the %-syntax:
d1=''.join(['%02x'%i for i in d])
print(d1)

# The more modern approach is the .format method:
d1=''.join(['{:02x}'.format(i) for i in d])
print(d1)

Result:

py -3 .\SO3\62087693.py
<class 'bytes'>
True
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
py -2 .\SO3\62087693.py
<type 'str'>
True
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147
3344af61e4473d60d85481bf822a6d045a8131075639babc6ebd510ea59f3b5aef932e915b41e21823100b59a1c9b63315e494902e62c38eb83f99c26147

Note: more recently, from Python 3.6 upwards there is a f-string syntax (but I had frozen at version 3.5.1 so this isn't proved by an example):

''.join([f'{i:02x}' for i in d])
JosefZ
  • 28,460
  • 5
  • 44
  • 83