Problem with base64 encoding in PHP and base64 decoding in Java

The string is "gACA" encoded in PHP using base64. Now I am trying to decode in java using base64. But get an absurd meaning after decoding. I tried like this:

public class DecodeString{
{
      public static void main(String args[]){
      String strEncode = "gACA";   //gACA is encoded string in PHP
      byte byteEncode[] = com.sun.org.apache.xerces.internal.impl.dv.util.Base64.decode(strEncode );
      System.out.println("Decoded String" + new String(k, "UTF-8"));
      }
 }

      

Output:    ??

Please help me

+3


source to share


4 answers


Java has a built-in Base64 encoder decoder, does not require additional libraries to decode it:

byte[] data = javax.xml.bind.DatatypeConverter.parseBase64Binary("gACA");
for (byte b : data)
    System.out.printf("%02x ", b);

      

Output:



80 00 80

      

These are 3 bytes with hexadecimal codes: 80 00 80

+1


source


Try it, this worked for me (but I decoded the files):

Base64.decodeBase64(IOUtils.toByteArray(strEncode));

      

So it will look like this:



public class DecodeString{
{
  public static void main(String args[]){
  String strEncode = "gACA";   //gACA is encoded string in PHP
  byte[] byteEncode = Base64.decodeBase64(IOUtils.toByteArray(strEncode));
  System.out.println("Decoded String" + new String(k, "UTF-8));
  }
}

      

Please note that you will need additional libraries:

+1


source


public static void main(String args[])  {

        String strEncode = "gACA";   //gACA is encoded string in PHP
        byte byteEncode[] = Base64.decode(strEncode);

        String result = new String(byteEncode, "UTF-8");
        char[] resultChar = result.toCharArray();
        for(int i =0; i < resultChar.length; i++)
        {
            System.out.println((int)resultChar[i]);
        }
        System.out.println("Decoded String: " + result);
    }

      

I suspect this is an encoding issue. Problem about 65533 in a C # text file to read , this post assumes the first and last characters are \ ". There is char 0 in the middle. Your result is probably" "or" 0 ", but with the wrong encoding.

+1


source


First of all, the code you are using doesn't have to compile, it skips the final quote after "UTF-8

.

And yes, "gACA"

is a valid string base64

as it goes along, but doesn't decode to any meaningful UTF-8 text. I assume you are using the wrong encoding or you have messed up the string in some way ...

0


source







All Articles