In java 8 learning series, we already learned about new way to read a file line by line using streams. Java 8 introduced one more good addition related to IO operations and that is Base64 support. I this post, we will learn about it.
What is Base 64 encoding?
When you have some binary data that you want to ship across a network, you generally don’t do it by just converting data into stream of bits and bytes over the network in a raw format. Why? because some media are designed for streaming text only. These protocols may interpret your binary data as control characters which they are not.
Base 64
encoding convert your binary data into 64 printable ASCII
characters. Generally it is done for binary data in email messages and "basic"
HTTP authentication. These 64 printable characters are:
- 26 uppercase letters [A…Z]
- 26 lowercase letters [a…z]
- 10 digits [0…9]
- 2 symbols [Read more]
The encoded string with above characters is safe to be transferred over network supporting text data without fear of losing data in confusion of control characters.
Base64 support before Java 8
For many years, java has provided support for base 64 via a non-public class (therefore non-usable) java.util.prefs.Base64
an undocumented class sun.misc.BASE64Encoder
. This class has also very limited information in public domain.
Base64 support from Java 8
Java 8 has added a class for Base 64 encoding and decoding purpose i.e. java.util.Base64. We will the code examples below for using it.
1) Encoding a string to base 64
This is as simple as getting an instance of encoder and input the string as bytes to encode it.
Base64.Encoder encoder = Base64.getEncoder(); String normalString = "username:password"; String encodedString = encoder.encodeToString( normalString.getBytes(StandardCharsets.UTF_8) ); Output: dXNlcm5hbWU6cGFzc3dvcmQ=
2) Decoding a base 64 encoded string
This is also very simple. Just get the instance of Base64.Decoder and use it to decode the base 64 encoded string.
String encodedString = "dXNlcm5hbWU6cGFzc3dvcmQ="; Base64.Decoder decoder = Base64.getDecoder(); byte[] decodedByteArray = decoder.decode(encodedString); //Verify the decoded string System.out.println(new String(decodedByteArray)); Output: username:password
3) Wrap to a base 64 encoded output stream
If you don’t want to directly work with data and rather prefer to work with streams, you can wrap the output stream such that all data written to this output stream will be automatically base 64 encoded.
Path originalPath = Paths.get("c:/temp", "mail.txt"); Path targetPath = Paths.get("c:/temp", "encoded.txt"); Base64.Encoder mimeEncoder = Base64.getMimeEncoder(); try(OutputStream output = Files.newOutputStream(targetPath)){ //Copy the encoded file content to target file Files.copy(originalPath, mimeEncoder.wrap(output)); //Or simply use the encoded output stream OutputStream encodedStrem = mimeEncoder.wrap(output); }
That’s all for this topic. This is already simple enough.
Happy Learning !!
Vikrant
How to encode image to base64 in java 8?
ravi
warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
How to solve this warning in java 6
Lokesh Gupta
You get the error because
sun.misc.BASE64Encoder
is an internal API of the JDK. It’s not part of the official public Java API, so you are not supposed to be using it. There’s no guarantee that in a future Java update this class will still exist, and in other Java implementations (for example IBM’s JVM) this class doesn’t exist. Use this implementation.ravi
Hi Lokesh,
I am attaching my method please check…
public String getEncryotedCC(String plainText) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException
{
DESKeySpec keySpec = new DESKeySpec(“Your secret Key phrase”.getBytes(“UTF8”));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(“DES”);
SecretKey key = keyFactory.generateSecret(keySpec);
BASE64Encoder base64encoder = new BASE64Encoder();
byte[] cleartext = plainText.getBytes("UTF8");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String encrypedString = base64encoder.encode(cipher.doFinal(cleartext));
System.out.println("encrypedPwd : " + encrypedString);
return encrypedString;
}