21

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?

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
toom
  • 12,864
  • 27
  • 89
  • 128
  • [Can't reproduce](http://ideone.com/z07TWN), an extra char on the end of the string would raise that exact exception ... – Alex K. Feb 09 '16 at 13:11
  • But from where are you getting the coded string? how do you pass it to the payload variable?, because as you say, it works... I've just tested it with Java 8 and no problems. – Eduardo Yáñez Parareda Feb 09 '16 at 13:11

3 Answers3

45

Okay, I found out. The original String is encoded on an Android device using android.util.Base64 by Base64.encodeToString(json.getBytes("UTF-8"), Base64.DEFAULT);. It uses android.util.Base64.DEFAULT encoding scheme.

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

toom
  • 12,864
  • 27
  • 89
  • 128
  • 2
    Do you know if there is the same problem the other way around? I mean, can we have an error if an Android device tries to read a String encoded by a Java implementation? – OlivierGrenoble Mar 28 '19 at 10:02
  • I had this problem moving from Mac (where `Base64.getDecoder` worked) to a Windows platform. Thanks for the solution! – Black May 19 '21 at 02:32
14

I was trying to use the strings from the args. I found that if I use arg[0].trim() that it made it work. eg

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

I guess there's some sort of whitespace that gets it messed up.

JustGage
  • 1,534
  • 17
  • 20
4

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:

String encode = Base64.encodeToString(src.getBytes(), Base64.NO_WRAP);
סטנלי גרונן
  • 2,917
  • 23
  • 46
  • 68