mascai
mascai

Reputation: 1872

Convert utf-8 string to base64

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

Upvotes: 0

Views: 2113

Answers (2)

tdelaney
tdelaney

Reputation: 77347

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)

Upvotes: 1

Frank Yellin
Frank Yellin

Reputation: 11285

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

Upvotes: 1

Related Questions