9

I am trying to use sun.misc.BASE64Encoder/Decoder, but this code:

(new sun.misc BASE64Encoder()).encode(new    
    sun.misc.BASE64Decoder().decodeBuffer("test string XML:"))

returns "test/string/XML/" I am embarrassed

Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
slavig
  • 339
  • 2
  • 6
  • 19

4 Answers4

22

Don't use sun.misc or com.sun classes. They are not guaranteed to be consistent between different versions of the jre.

Use commons-codec Base64.encodeBase64(..) and Base64.decodeBase64(..)

Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
  • hehe.. I sent my recent project in which sun.misc.BASE64Encoder/Decoder used to a customer. Didn't know about inconsistency in different jre's. I hope it's a rare issue. – Roman Feb 15 '10 at 16:14
  • 2
    It's actually been working fine since JDK 1.1, but it's still ugly to use internal APIs. From a purely practical standpoint, you have nothing to worry about. – Tomer Gabel Jun 15 '11 at 19:42
  • 2
    Why not to use sun.* packages: http://www.oracle.com/technetwork/java/faq-sun-packages-142232.html – justderb Mar 06 '14 at 22:40
15

Use Class:

javax.xml.bind.DatatypeConverter

It has 2 methods of interest:

public static byte[] parseBase64Binary( String lexicalXSDBase64Binary )
public static String printBase64Binary( byte[] val )
Chandra Sekhar
  • 15,838
  • 10
  • 67
  • 89
Diego
  • 151
  • 1
  • 2
7

You first decoding the string "test string XML:", which isn't really valid Base64, since it contains spaces and a colon, none of which are valid B64 characters. I think that you meant to encode then decode, like this:

(new sun.misc.BASE64Decoder().decodeBuffer(new sun.misc.BASE64Encoder().encode("test string XML:"))
JSBձոգչ
  • 39,735
  • 16
  • 97
  • 166
1

I think you want:

String s = "Hello world";
new sun.misc.BASE64Encoder().encode(s.getBytes("UTF-8"));

Even better, use the commons utils as the previous answer suggested. Only use sun.misc.Base64Encoder if you can't afford to add the external dependency on another jar.

George Armhold
  • 30,424
  • 49
  • 151
  • 227