I have a string that is base64 encoded. It looks like this:
eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0=
Any online tool can decode this to the proper string 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'm getting the following error:
payload = eyJibGExIjoiYmxhMSIsImJsYTIiOiJibGEyIn0=
java.lang.IllegalArgumentException: Input byte array has incorrect ending byte at 40
What is wrong with my code?
Okay, I found out. The original String is encoded on an Android device using
android.util.Base64
byBase64.encodeToString(json.getBytes("UTF-8"), Base64.DEFAULT);
. It usesandroid.util.Base64.DEFAULT
encoding scheme.Then on the server side when using
java.util.Base64
this has to be decoded withBase64.getMimeDecoder().decode(payload)
not withBase64.getDecoder().decode(payload)
Maybe too late, but I also had this problem.
By default, the Android Base64 util adds a newline character to the end of the encoded string.
The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character.
Your android app should encode
src
something like this:I was trying to use the strings from the args. I found that if I use
arg[0].trim()
that it made it work. egI guess there's some sort of whitespace that gets it messed up.