3

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?

Mikalai Lushchytski
  • 1,563
  • 1
  • 9
  • 18
Vlenovil
  • 35
  • 5

2 Answers2

2

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.

flaxel
  • 4,173
  • 4
  • 17
  • 30
  • 1
    Converting bytes to and from a String without a Charset is not portable across platforms—it will do different things on Windows than on other systems. – VGR Oct 01 '20 at 11:46
  • Thanks for the tip. If `getBytes` is called, the default charset of the operating system would be used. – flaxel Oct 01 '20 at 11:53
1

The documentation for Base64.Decoder says:

The Base64 padding character '=' is accepted and interpreted as the end of the encoded byte data, but is not required.

So any base 64 sequence encoded without padding will be accepted by Base64.Decoder.

VGR
  • 40,506
  • 4
  • 48
  • 63