英文:
Java equivalent of PHP code return different base 64 encoding result
问题
$completeStrBytes = array();
$completeStrBytes[0] = ($signatureLength >> 8) & 0xFF; // signatureLength = 128
$completeStrBytes[1] = $signatureLength;
echo base64_encode(implode('', $completeStrBytes));
输出:AIA=
英文:
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.
答案1
得分: 0
如果您在Java中处理计算2字节数组 { 0x00, 0x80 }
的base64,而在php中则对一个由两个数字字符串连接而成的4字符字符串 "0128"
进行base64计算。
您可能首先想要将这些数字转换为字符:
var_dump(base64_encode(chr($firstPart) . chr($secondPart))); // string(4) "AIA="
更新
您还可以使用函数 pack 将不同的数据类型转换为字符串:
<?php
$signatureLength = 128;
var_dump(base64_encode(pack('n', $signatureLength))); // string(4) "AIA="
英文:
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="
答案2
得分: 0
注意,还有一种base64url
编码,这与PHP中的base64_encode()
不同。
当你在例如JWT编码/解码的情况下使用PHP的base64_encode()
时,会遇到麻烦。
所以针对你的情况,尝试使用
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);
}
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论