7

I tried to decode the utf-8 string which I encoded successfully but can't figure out how to decode it... Actually it's decoded very well, but I just want to concatenate it with like:

b = base64.b64decode(a).decode("utf-8", "ignore")
print('Decoding:'+b)

as I did in by doing encoding

a = str(base64.b64encode(bytes('hasni zinda ha u are my man boy yes u are ', "utf-8")))
print('Encoding :'+a)

Whenever i try to do it in the way which i want it gives me the error about :

File "C:/Users/…/python/first.py", line 8, in <module>
  b = base64.b64decode(a).decode("utf-8", "ignore")
File "C:\Users\…\AppData\Local\Programs\Python\Python36-32\lib\base64.py", line 87, in b64decode
  return binascii.a2b_base64(s) binascii.Error: Incorrect padding

Can anyone please help me to resolve it?

2
  • 1
    That Incorrect padding error comes from the base64 part of your code, take a look at stackoverflow.com/questions/4080988/… I suggest that you break your code into individual function calls instead of call chains—that’ll make it easier to debug and understand. Commented Jan 20, 2018 at 5:20
  • Incorrect padding caused by incorrect number of length in string. For base64, length should be divisible by 4. Otherwise, you have to pad with '=' at the end to make it such length. Please find more information here Commented Jan 20, 2018 at 5:20

1 Answer 1

11

Follow-up to my comment above.

You have to reverse the sequence of operation when you decode a Base64 encoded string:

>>> s = "hasni zinda ha u are my man boy yes u are "
# Encode the Python str into bytes.
>>> b = s.encode("utf-8")
# Base64 encode the bytes.
>>> s_b64 = base64.b64encode(b)
>>> print("Encoding: " + str(s_b64))
Encoding: b'aGFzbmkgemluZGEgaGEgdSBhcmUgbXkgbWFuIGJveSB5ZXMgdSBhcmUg'

Now that you have the encoded string, decoding works in reverse order:

# Base64 decode the encoded string into bytes.
>>> b = base64.b64decode(s_b64)
# Decode the bytes into str.
>>> s = b.decode("utf-8")
print("Decoding: " + s)
Decoding: hasni zinda ha u are my man boy yes u are 

For more details, please see the documentation for b64encode() and b64decode(), as well as the Output padding section for Base64 (required to ensure that a Base64 encoded string’s length is divisible by 4).

To use your two-liners:

>>> a = base64.b64encode(bytes("hasni zinda ha u are my man boy yes u are ", "utf-8"))
>>> print("Encoding:", a)
Encoding: b'aGFzbmkgemluZGEgaGEgdSBhcmUgbXkgbWFuIGJveSB5ZXMgdSBhcmUg'
>>> b = base64.b64decode(a).decode("utf-8")
>>> print("Decoding:", b)
Decoding: hasni zinda ha u are my man boy yes u are 
Sign up to request clarification or add additional context in comments.

1 Comment

base64.b64decode(a).decode("utf-8") is the gold!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.