Brent Martin Miller
Brent Martin Miller

Reputation: 83

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

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?

Upvotes: 2

Views: 1423

Answers (2)

swpalmer
swpalmer

Reputation: 4380

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, 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));

Upvotes: 1

Frandall
Frandall

Reputation: 418

Based on this answer how about specify the encoding. Recommended encoding is UTF-8.

Upvotes: 0

Related Questions