简体   繁体   中英

Java equivalent of PHP code return different base 64 encoding result

Java Code

completeStrBytes = new byte[2];
completeStrBytes[0] = (byte)(signatureLength>>>8); //signatureLength = 128
completeStrBytes[1] = (byte)signatureLength;
System.out.println(Base64.getEncoder().encodeToString(completeStrBytes));

output: AIA=

PHP Code

$firstPart = $signatureLength >> 8;
$secondPart = $signatureLength;
var_dump(base64_encode($firstPart . $secondPart));

output: string(8) "MDEyOA=="

I understand PHP string already treat as byte string.

May I know how to get java equivalent code in PHP? what's wrong in the PHP code?

Thanks in advance.

If the case of Java you're calculating base64 for 2-byte array { 0x00, 0x80 } . In case of php you're calculation base64 for a 4-character string "0128" (which you got when concatenated two numbers as strings).

You probably want to convert those numbers to chars first:

  var_dump(base64_encode(chr($firstPart) . chr($secondPart))); // string(4) "AIA="

UPD

You also may want to use function pack to convert different data types into a string:

<?php
  $signatureLength = 128;
  var_dump(base64_encode(pack('n', $signatureLength))); // string(4) "AIA="

Note that there is also a base64url encoding, which is NOT the base64_encode() from PHP.

When you use PHP base64_encode() for example for JWT encoding/decoding, you will get into trouble.

So for your case try

var_dump(base64url_encode($firstPart . $secondPart));
function base64url_encode($data)
{
    $b64 = base64_encode($data);
    if ($b64 === false) {
        return false;
    }
    $url = strtr($b64, '+/', '-_');
    return rtrim($url, '=');
}

function base64url_decode($data, $strict = false)
{
    $b64 = strtr($data, '-_', '+/');
    return base64_decode($b64, $strict);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM