Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

work sun.misc.BASE64Encoder/Decoder for getting byte[]

Tags:

java

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

like image 313
slavig Avatar asked Feb 15 '10 15:02

slavig


People also ask

Is there an alternative to Sunsun Base64 encoder?

Sun / Oracle said it was a bad idea. There were always alternatives. The JDK 11 replacement for sun.misc.BASE64Encoder and sun.miscBASE64Decoder is java.util.Base64.Encoder and java.util.Base64.Decoder. String encoded = new BASE64Encoder ().encode (bBytes); byte [] decoded = new BASE64Decoder ().decodeBuffer (encoded);

How to decode a Base64 encoded string?

Decodes a Base64 encoded String into a newly-allocated byte array using the Base64 encoding scheme. Decodes all bytes from the input byte buffer using the Base64 encoding scheme, writing the results into a newly-allocated ByteBuffer. Returns an input stream for decoding Base64 encoded byte stream.

What is the JDK 11 replacement for Base64 encoder and decoder?

The JDK 11 replacement for sun.misc.BASE64Encoder and sun.miscBASE64Decoder is java.util.Base64.Encoder and java.util.Base64.Decoder. String encoded = new BASE64Encoder ().encode (bBytes); byte [] decoded = new BASE64Decoder ().decodeBuffer (encoded); The JDK 11 replacements which would generate identical values are: import java.util.Base64; // ...

How fast is Base64 encoded in Java 8?

In the actual test of encoding and decoding speed, Base64 provided by Java 8 is at least 11 times faster than that provided by sun.mis c suite and at least 3 times faster than that provided by Apache Commons Codec.


2 Answers

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(..)

like image 169
Bozho Avatar answered Oct 15 '22 02:10

Bozho


Use Class:

javax.xml.bind.DatatypeConverter

It has 2 methods of interest:

public static byte[] parseBase64Binary( String lexicalXSDBase64Binary )
public static String printBase64Binary( byte[] val )
like image 21
Diego Avatar answered Oct 15 '22 01:10

Diego