Search code examples
javaencodingcharacter-encodingdecodestring-decoding

Issue with Encoding base64 in PHP and Decoding base64 in Java


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


Solution

  • 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