简体   繁体   中英

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

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?

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 .

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