I want to encode and decode a string into base64 without padding.
it's correct following code?
String test = Base64.getUrlEncoder().withoutPadding().encodeToString(test);
String output = Base64.getUrlDecoder().decode(test);
The lenght without padding always be correct in decoding?
If you want to encode and decode a string variable, you can use the following code:
String s = "test";
String test = Base64.getUrlEncoder().withoutPadding().encodeToString(s.getBytes(StandardCharsets.UTF_8)); // dGVzdA
String output = new String(Base64.getUrlDecoder().decode(test), StandardCharsets.UTF_8); // test
You can get more information about Base64 in this post. There is also a nice post about padding characters. And I found a short tutorial from JavaCodeGeeks:
By default, encoding pads with the ‘=’ double equal operator if the encoded string length is not met the desired length.
Typically, an encoded string should be multiples of 3 otherwise it will be added with = character.
On the other side, while decoding all extra padded characters will be discarded.
If you do want to be decoded then encode without padding using withoutPadding().
withoutPadding() method helps to skip the padding of the output.
Many developers think that no padding encoded string cannot be decoded back to the original string.
But, it is wrong and Base64.Decode api provides flexibility to decode back.
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