Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

base64 encoded string: can be decoded in PHP but not Java?

Tags:

java

php

base64

PHP code that works:

$str = "528ABf4cCU5g7zKzLC2t8oze4mstEcWKErar6FbTK2Xo97bu17S8cDmEg5HlbgcLtfvKCVvJ4FnRV3R1iX1TWZIyM7T2352wsb6LUyqFXA03Fz9G6dQmhRrkWpOXAoHeU/H63LKKzcJDhNb3YI2hfsU20BcT0qkk74XKneC7D91OKY=";
echo strlen(base64_decode($str));

That outputs 130.

Java code that doesn't work:

String demo = "528ABf4cCU5g7zKzLC2t8oze4mstEcWKErar6FbTK2Xo97bu17S8cDmEg5HlbgcLtfvKCVvJ4FnRV3R1iX1TWZIyM7T2352wsb6LUyqFXA03Fz9G6dQmhRrkWpOXAoHeU/H63LKKzcJDhNb3YI2hfsU20BcT0qkk74XKneC7D91OKY=";
System.out.println(java.util.Base64.getDecoder().decode(demo).length);

This throws:

"Input byte array has wrong 4-byte ending unit" java.lang.IllegalArgumentException.

How can I make the base64 encoded string that PHP likes decodable by Java?

like image 425
neubert Avatar asked Nov 24 '25 21:11

neubert


1 Answers

That demo input is incorrectly padded; it should end in == instead of =.

You could use a more lenient decoder like Guava's BaseEncoding.

Alternatively, since padding is optional in Base64, you could just strip any trailing = characters before decoding with java.util.Base64.

like image 179
dnault Avatar answered Nov 26 '25 09:11

dnault



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!