Base64 Encryption Java
Java 8 included Base64 encoder in util package to achieve encoing. Base64 class implements encoder for encoding byte data using Base64 encoding scheme as specified in RFC 4648 and RFC 2045.
Thes instances of the Base64.Encoder class is safe if you are using multiple concurrent threads. Important point to note that if you pass pass null argument to method of this class it will throw NullPointerException exception. Below is sample class to encrypt and decrypt string value:
- Base64Encryption.java:
import java.nio.charset.Charset; import java.util.Base64; public class Base64Encryption { public static void main(String[] args) { String encryptMe = "Java Honk"; String encryptedString = base64Encode(encryptMe); String decryptedString = base64Decode(encryptedString); System.out.println("Original String: "+ encryptMe); System.out.println("Encrypted String: "+ encryptedString); System.out.println("Decrypted String: "+ decryptedString); } /** * @param token * @return encoded */ public static String base64Encode(String token) { return Base64.getEncoder().encodeToString(token.getBytes()); } /** * @param token * @return */ public static String base64Decode(String token) { byte [] decodedBytes = Base64.getDecoder().decode(token.getBytes()); return new String(decodedBytes, Charset.forName("UTF-8")); } }
- Output: