Base64: an input byte array has an invalid final byte of 40

I have a base64 encoded string. It looks like this:

eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0= 

Any online tool can decode this to the desired line, which is {"bla1":"bla1","bla2":"bla2"} . However, my Java implementation fails:

 import java.util.Base64; System.out.println("payload = " + payload); String json = new String(Base64.getDecoder().decode(payload)); 

I get the following error:

 payload = eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0= java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 40 

What is wrong with my code?

+5
source share
2 answers

Ok, I found out. The source string is encoded on an Android device using android.util.Base64 on Base64.encodeToString(json.getBytes("UTF-8"), Base64.DEFAULT); . It uses the android.util.Base64.DEFAULT coding scheme.

Then on the server side when using java.util.Base64 this should be decoded using Base64.getMimeDecoder().decode(payload) not with Base64.getDecoder().decode(payload)

+8
source

I tried to use strings from args. I found that if I use arg[0].trim() so that it arg[0].trim() . eg,

 Base64.getDecoder().decode(arg[0].trim()); 

I assume that there are some gaps that confused him.

0
source

Source: https://habr.com/ru/post/1242620/


All Articles