I'm trying to decode a simple Base64 string, but am unable to do so. I'm currently using the org.apache.commons.codec.binary.Base64
package.
The test string I'm using is: abcdefg
, encoded using PHP YWJjZGVmZw==
.
This is the code I'm currently using:
Base64 decoder = new Base64(); byte[] decodedBytes = decoder.decode("YWJjZGVmZw=="); System.out.println(new String(decodedBytes) + "\n") ;
The above code does not throw an error, but instead doesn't output the decoded string as expected.
To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.
Encoder using getEncoder() and then get the encoded string by passing the byte value of actualString in encodeToString() method as parameter. byte[] actualByte= Base64. getDecoder(). decode(encodedString);
Java 8 now has inbuilt encoder and decoder for Base64 encoding. In Java 8, we can use three types of Base64 encoding. Simple − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/.
Modify the package you're using:
import org.apache.commons.codec.binary.Base64;
And then use it like this:
byte[] decoded = Base64.decodeBase64("YWJjZGVmZw=="); System.out.println(new String(decoded, "UTF-8") + "\n");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With