Is Java 8 java.util.Base64 a drop-in replacement for sun.misc.BASE64?

前端 未结 4 1617
遇见更好的自我
遇见更好的自我 2020-12-25 11:00

Question

Are the Java 8 java.util.Base64 MIME Encoder and Decoder a drop-in replacement for the unsup

4条回答
  •  借酒劲吻你
    2020-12-25 11:26

    Here's a small test program that illustrates a difference in the encoded strings:

    byte[] bytes = new byte[57];
    String enc1 = new sun.misc.BASE64Encoder().encode(bytes);
    String enc2 = new String(java.util.Base64.getMimeEncoder().encode(bytes),
                             StandardCharsets.UTF_8);
    
    System.out.println("enc1 = <" + enc1 + ">");
    System.out.println("enc2 = <" + enc2 + ">");
    System.out.println(enc1.equals(enc2));
    

    Its output is:

    enc1 = 
    enc2 = 
    false
    

    Note that the encoded output of sun.misc.BASE64Encoder has a newline at the end. It doesn't always append a newline, but it happens to do so if the encoded string has exactly 76 characters on its last line. (The author of java.util.Base64 considered this to be a small bug in the sun.misc.BASE64Encoder implementation – see the review thread).

    This might seem like a triviality, but if you had a program that relied on this specific behavior, switching encoders might result in malformed output. Therefore, I conclude that java.util.Base64 is not a drop-in replacement for sun.misc.BASE64Encoder.

    Of course, the intent of java.util.Base64 is that it's a functionally equivalent, RFC-conformant, high-performance, fully supported and specified replacement that's intended to support migration of code away from sun.misc.BASE64Encoder. You need to be aware of some edge cases like this when migrating, though.

提交回复
热议问题