Encoding as Base64 in Java Encoding as Base64 in Java java java

Encoding as Base64 in Java


You need to change the import of your class:

import org.apache.commons.codec.binary.Base64;

And then change your class to use the Base64 class.

Here's some example code:

byte[] encodedBytes = Base64.encodeBase64("Test".getBytes());System.out.println("encodedBytes " + new String(encodedBytes));byte[] decodedBytes = Base64.decodeBase64(encodedBytes);System.out.println("decodedBytes " + new String(decodedBytes));

Then read why you shouldn't use sun.* packages.


Update (2016-12-16)

You can now use java.util.Base64 with Java 8. First, import it as you normally do:

import java.util.Base64;

Then use the Base64 static methods as follows:

byte[] encodedBytes = Base64.getEncoder().encode("Test".getBytes());System.out.println("encodedBytes " + new String(encodedBytes));byte[] decodedBytes = Base64.getDecoder().decode(encodedBytes);System.out.println("decodedBytes " + new String(decodedBytes));

If you directly want to encode string and get the result as encoded string, you can use this:

String encodeBytes = Base64.getEncoder().encodeToString((userName + ":" + password).getBytes());

See Java documentation for Base64 for more.


Use Java 8's never-too-late-to-join-in-the-fun class: java.util.Base64

new String(Base64.getEncoder().encode(bytes));


In Java 8 it can be done as:Base64.getEncoder().encodeToString(string.getBytes(StandardCharsets.UTF_8))

Here is a short, self-contained complete example:

import java.nio.charset.StandardCharsets;import java.util.Base64;public class Temp {    public static void main(String... args) throws Exception {        final String s = "old crow medicine show";        final byte[] authBytes = s.getBytes(StandardCharsets.UTF_8);        final String encoded = Base64.getEncoder().encodeToString(authBytes);        System.out.println(s + " => " + encoded);    }}

Output:

old crow medicine show => b2xkIGNyb3cgbWVkaWNpbmUgc2hvdw==