Base64 Encoding: Illegal base64 character 3c

2020-08-19 03:15发布

问题:

I am trying to decode data in an xml format into bytes base64 and I am having an issues. My method is in java which takes a String data and converts it into bytes like as bellow.

String data = "......"; //string of data in xml format
byte[] dataBytes = Base64.getDecoder().decode(data);

Which failed and gave the exception like bellow.

java.lang.IllegalArgumentException: Illegal base64 character 3c
    at java.util.Base64$Decoder.decode0(Base64.java:714)
    at java.util.Base64$Decoder.decode(Base64.java:526)
    at java.util.Base64$Decoder.decode(Base64.java:549)
    at XmlReader.main(XmlReader.java:61)

Is the xml format not compatible with base64?

回答1:

Just use this method

getMimeDecoder()

String data = "......";
byte[] dataBytes =  Base64.getMimeDecoder().decode(data);


回答2:

I got this same error and problem was that the string was starting with data:image/png;base64, ...

The solution was:

byte[] imgBytes = Base64.getMimeDecoder().decode(imgBase64.split(",")[1]);


回答3:

You should first get the bytes out of the string (in some character encoding).

For these bytes you use the encoder to create the Base64 representation for that bytes.

This Base64 string can then be decoded back to bytes and with the same encoding you convert these bytes to a string.

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64Example {

  public static void main(String[] args) {
    final String xml = "<root-node><sub-node/></root-node>";
    final byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8);
    final String xmlBase64 = Base64.getEncoder().encodeToString(xmlBytes);
    System.out.println(xml);
    System.out.println(xmlBase64);

    final byte[] xmlBytesDecoded = Base64.getDecoder().decode(xmlBase64);
    final String xmlDecoded = new String(xmlBytesDecoded, StandardCharsets.UTF_8);
    System.out.println(xmlDecoded);
  }

}

Output is:

<root-node><sub-node/></root-node>
PHJvb3Qtbm9kZT48c3ViLW5vZGUvPjwvcm9vdC1ub2RlPg==
<root-node><sub-node/></root-node>


回答4:

Thanks to @luk2302 I was able to resolve the issue. Before decoding the string, I need to first encode it to Base64

    byte[] dataBytes = Base64.getEncoder().encode(data.getBytes());
    dataBytes = Base64.getDecoder().decode(dataBytes);