Java Base64 Encode function the same as PHP Base64 Encode function?

Brent Miller :

I'm trying to test a Soap Security header in PHP with values supplied by the client.

They are supplying a value like...

wTAmCL9tmg6KNpeAQOYubw==

...and saying it's a Base64 encoded value.

However, when I run it through PHP's Base64 decode function...

base64_decode("wTAmCL9tmg6KNpeAQOYubw==");

it translates it as: �0&�m6@�.o

If I decode it in Java...

import java.util.Base64;
import java.util.Arrays;

/**
 * hello
 */
public class hello {

    public static void main(String[] args) {
        Base64.Decoder decoder = Base64.getDecoder();
        Base64.Encoder encoder = Base64.getEncoder();
        String stringEncoded = "wTAmCL9tmg6KNpeAQOYubw==";

        System.out.println("This is a decoded value: " + decoder.decode(stringEncoded));
        System.out.println("This is a re-coded value: " + encoder.encode(decoder.decode(stringEncoded)));

    }
}

I get a decoded string like this: [B@7229724f

But then if I try to re-encode that string, I get this: [B@4c873330

What am I missing here?

swpalmer :

What you are missing is that the result of decoding the Base 64 value is not intended to be printed as a String. In fact, the you see this in the output of the Java println. That [B@7229724f is not a string representation of the decoded bytes. It is the way a Java byte [] prints. The [B indicates a byte array, and the remaining characters are the hexadecimal digits of the object identity. (It will print differently for every byte array instance and has nothing to do with the contents of the array.)

If you want the String representation of the bytes you will need to construct a String from the bytes:

    System.out.println("This is a decoded value: " + new String(decoder.decode(stringEncoded), StandardCharsets.UTF_8));
    System.out.println("This is a re-coded value: " + new String(encoder.encode(decoder.decode(stringEncoded), StandardCharsets.UTF_8));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=161483&siteId=1