0

I converted base64 str1= eyJlbXBsb3llciI6IntcIm5hbWVcIjpcInVzZXJzX2VtcGxveWVyXCIsXCJhcmdzXCI6XCIxMDQ5NTgxNjI4MzdcIn0ifQ

to str2={"employer":"{\"name\":\"users_employer\",\"args\":\"104958162837\"}"}

with help of http://www.online-decoder.com/ru

I want to convert str2 to str1 with help of python. My code:

import base64

data = """{"employer":"{"name":"users_employer","args":"104958162837"}"}"""
encoded_bytes = base64.b64encode(data.encode("utf-8"))
encoded_str = str(encoded_bytes, "utf-8")
print(encoded_str)

The code prints str3=

eyJlbXBsb3llciI6InsibmFtZSI6InVzZXJzX2VtcGxveWVyIiwiYXJncyI6IjEwNDk1ODE2MjgzNyJ9In0=

What should I change in code to print str1 instead of str3 ?

I tried

{"employer":"{\"name\":\"users_employer\",\"args\":\"104958162837\"}"}

and

{"employer":"{"name":"users_employer","args":"104958162837"}"}

but result is the same

mascai
  • 1,373
  • 1
  • 9
  • 30

2 Answers2

1

The results you want are just base64.b64decode(str1 + "=="). See this post for more information on the padding.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
  • I did ```data = data + "==" encoded_bytes = base64.b64encode(data.encode("utf-8"))``` But result is not good(. What I did wrong? – mascai Nov 24 '20 at 00:19
  • The python decoder requires that you pad the string with "=", but the unpadded string is different up to the pad point. Just adding padding won't change the fact that they are different. – tdelaney Nov 24 '20 at 00:23
1

The problem is that \" is a python escape sequence for the single character ". The fix is to keep the backslashes and use a raw string (note the "r" at the front).

data = r"""{"employer":"{\"name\":\"users_employer\",\"args\":\"104958162837\"}"}"""

This will be the original string, except that python pads base64 numbers to 4 character multiples with the "=" sign. Strip the padding and you have the original.

import base64

str1 = "eyJlbXBsb3llciI6IntcIm5hbWVcIjpcInVzZXJzX2VtcGxveWVyXCIsXCJhcmdzXCI6XCIxMDQ5NTgxNjI4MzdcIn0ifQ"
str1_decoded = base64.b64decode(str1 + "="*divmod(len(str1),4)[1]).decode("ascii")
print("str1", str1_decoded)

data = r"""{"employer":"{\"name\":\"users_employer\",\"args\":\"104958162837\"}"}"""
encoded_bytes = base64.b64encode(data.encode("utf-8"))
encoded_str = str(encoded_bytes.rstrip(b"="), "utf-8")
print("my encoded", encoded_str)
print("same?", str1 == encoded_str)
tdelaney
  • 73,364
  • 6
  • 83
  • 116