简体   繁体   中英

getUrlEncoder/getUrlDecoder proplem padding in Java

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.

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.

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