Base64 encoding/decoding?

Example 1

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


Base64 base64 = new Base64();
		return new String(base64.encode(new String(AUTH_STRING_PROXY).getBytes()));

Example 2


sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encodedUserPwd = encoder.encode("username:password".getBytes());
connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);

Java 8 now provides an additional utility class for this java.util.Base64

byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
byte[] decoded = Base64.getDecoder().decode(encoded);

System.out.println(encoded);
System.out.println(new String(decoded, StandardCharsets.UTF_8));

Output

aGVsbG8gd29ybGQ=
hello world

Java 6 and 7

Since Java 6 you can use the lesser known class javax.xml.bind.DatatypeConverter. This is part of the JRE, no extra libraries required.

byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
byte[] decoded = DatatypeConverter.parseBase64Binary(encoded);

System.out.println(encoded);
System.out.println(new String(decoded, "UTF-8"));

Output

aGVsbG8gd29ybGQ=
hello world
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s