4

A string-"gACA" encoded in PHP using base64. Now I'm trying to decode in java using base64. But getting absurd value after decoding. I have 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 out

Samraan
  • 204
  • 1
  • 2
  • 14

5 Answers5

2

Java has built-in Base64 encoder-decoder, no need extra 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

It's 3 bytes with hexadecimal codes: 80 00 80

icza
  • 389,944
  • 63
  • 907
  • 827
1

Try this, it worked fine for me (However I was decoding files):

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

So it would 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));
  }
}

Note that you will need extra libraries:

Drumnbass
  • 867
  • 1
  • 14
  • 35
1
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 it's an encoding problem. Issue about 65533 � in C# text file reading this post suggest the first and last character are \“. In the middle there is a char 0. Your result is probably "" or "0", but with wrong encoding.

Community
  • 1
  • 1
JohannisK
  • 535
  • 2
  • 10
0

First things first, the code you use should not compile, it's missing a closing quote after "UTF-8.

And yeah, "gACA" is a valid base64 string as the format goes, but it doesn't decode to any meaningful UTF-8 text. I suppose you're using the wrong encoding, or messed up the string somehow...

0

RFC 4648 defines two alphabets.

  1. PHP uses Base 64 Encoding
  2. Java uses Base 64 Encoding with URL and Filename Safe Alphabet.

They are very close but not the exact same. In PHP:

const REPLACE_PAIRS = [
  '-' => '+',
  '_' => '/'
];
public static function base64FromUrlSafeToPHP($base64_url_encoded) {
  return strtr($base64_url_encoded, self::REPLACE_PAIRS);
}

public static function base64FromPHPToUrlSafe($base64_encoded) {
  return strtr($base64_encoded, array_flip(self::REPLACE_PAIRS));
}
chx
  • 11,270
  • 7
  • 55
  • 129