Difference between getEncoder and getUrlEncoder, getDecoder and getUrlDecoder in Java8 java.util.Base64 class

Difference between getEncoder and getUrlEncoder, getDecoder and getUrlDecoder in Java8 java.util.Base64 class

Starting with Java 8, encoding & decoding can be done using the java.util.Base64 class.

Base64.getEncoder().encode("hoge".getBytes());

This will do the encoding. There is another getUrlEncoder() method, which also performs encoding.

Base64.getUrlEncoder().encode("hoge".getBytes());

Difference between getEncoder and getUrlEncoder

The difference between getEncoder and getUrlEncoder is whether or not the Url is safe.

method Url Safe
getEncoder ×
getUrlEncoder

In the case of Url-safe, “+” is replaced by “-” and “/” by “_”; in the case of Url-unsafe, “+” and “/” are used as they are.

The difference between getDecoder and getUrlDecoder is the same.

Therefore, only if the encoded content does not contain “+” and “/”, it can be decoded correctly by getUrlDecoder when it is encoded by getEncoder.

The following is a sample code.

package purejava;

import java.util.Base64;

public class Base64Smaple {
  public static void main(final String[] args) {
    String in = "hogefuga";
    var encodeData = Base64.getEncoder().encode(in.getBytes()); // encode
    System.out.println(encodeData); // byte array

    var decodeData1 = new String(Base64.getDecoder().decode(encodeData));
    System.out.println(decodeData1); // hogefuga

    var decodeData2 = new String(Base64.getUrlDecoder().decode(encodeData));
    System.out.println(decodeData2); // hogefuga Can be decoded normally.
  }
}

However, if the result encoded by getEncoder contains “+” or “/”, decoding by getUrlDecoder will result in an error.

The same error may occur when encoding with getUrlEncoder and decoding with getDecoder. (Only when “-” and “_” are included.)

The following is a sample code that encodes with getEncoder and decodes with getUrlDecoder, resulting in an error.

package purejava;

import java.util.Base64;

public class Base64Smaple {

  public static void main(String[] args) {
    String in = "d!\"#$%&'()=~|";
    var encodeData = Base64.getEncoder().encode(in.getBytes()); // encode 
    System.out.println(new String(encodeData)); // ZCEiIyQlJicoKT1+fA== Contains "+".

    var decodeData1 = new String(Base64.getUrlDecoder().decode(encodeData)); // Error occurs because it cannot be decoded properly.
    // java.lang.IllegalArgumentException: Illegal base64 character 2b
    System.out.println(decodeData1);
  }
}

If you modify the decoding on line 12 of the above source to getDecoder, it will decode correctly.

コメント

Discover more from 株式会社CONFRAGE ITソリューション事業部

Subscribe now to keep reading and get access to the full archive.

Continue reading

Copied title and URL