iazaran
iazaran

Reputation: 216

Base64 of byte array in Java and it's equivalent in PHP

I want to simulate this JAVA code:

String auth = "ec65450a-5:5217e";
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
String authHeader = "Basic " + new String(encodedAuth);

to the PHP like this:

$string = 'ec65450a-5:5217e';
$bytes = array();
$bytes = unpack('C*', $string);
$authHeader = 'Basic ' . base64_encode(implode('', $bytes));

But PHP code generate another value.

Upvotes: 2

Views: 1765

Answers (2)

Alex Howansky
Alex Howansky

Reputation: 53636

PHP will already treat $string as a byte string, so you don't need to unpack/implode it.

If you do this:

$string = 'ec65450a-5:5217e';
$bytes = unpack('C*', $string);
echo implode('', $bytes);

You get this:

1019954535253489745535853504955101

Which is a mushed together list of integer base 10 ASCII values of each character, and is almost certainly not what you want. Just encode the string directly:

echo base64_encode($string);

Result:

ZWM2NTQ1MGEtNTo1MjE3ZQ==

Also, you'll want to change your password now that you've posted it here. :)

Upvotes: 2

ahoxha
ahoxha

Reputation: 1938

Check the character set that the encoders (Java and PHP) are using.

JavaDoc for the : getBytes() method of the String class.

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

The behavior of this method when this string cannot be encoded in the default charset is unspecified.

The java.nio.charset.CharsetEncoder class should be used when more control over the encoding process is required.

Returns:The resultant byte array

Since:JDK1.1

If you want to use a specific character set, you can pass it over to the method:

"test".getBytes(StandardCharsets.UTF_8);

Example This code produces two different values:

String s = "ec65450a-5:5217e";
System.out.println(Base64.getEncoder().encodeToString(s.getBytes()));
System.out.println(Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8)));
System.out.println(Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_16)));

Output

ZWM2NTQ1MGEtNTo1MjE3ZQ==

ZWM2NTQ1MGEtNTo1MjE3ZQ==

/v8AZQBjADYANQA0ADUAMABhAC0ANQA6ADUAMgAxADcAZQ==

The first two are the same, because getBytes() uses the platform's default charset, and it happens to be UTF-8

Upvotes: 1

Related Questions