Saturday, November 23, 2019

Base64 Encoding Too Decoding Event Inward Coffee Viii Too Before

Though, at that topographic point are a pair of ways to Base64 encode a String inward Java e.g. past times using Java 6's javax.xml.bind.DatatypeConverter#printBase64Binary(byte[]) or past times using Apache Commons Codec's Base64.encodeBase64(byte[) too Base64.decodeBase64(byte[])as shown here, or the infamous Sun's internal base64 encoder too decoder, sun.misc.BASE64Encoder().encode() too sun.misc.BASE64Decoder().decode(), at that topographic point was no measure agency inward JDK API itself. That was 1 of the few missing exceptional (another 1 is near joining string) which is addressed inward Java 8. The JDK 8 API contains a Base64 class inward java.util parcel which supports both encoding too decoding text inward Base64. You tin purpose Base64.Encoder to encode a byte array or String too Base64.Decoder to decode a base64 encoded byte array or String inward Java 8.

The JDK 8 API besides provides unlike types of Base64 encoder e.g. basic, URL too MIME to back upward unlike needs. I'll say you lot what is the departure betwixt Basic, URL too MIME Base64 encoder too why you lot necessitate inward this article, but earlier that let's revise what is base64 encoding itself?

The Base64 Encoding is an encoding system which uses 64 printable characters (A-Za-z0-9+/) to supervene upon each grapheme inward master copy String inward an algorithmic agency thence that it tin endure decoded later. The procedure which converts master copy String to something else is known every bit encoding too the contrary procedure to convert an encoded String to master copy content is known every bit decoding.

You tin farther read, Code: The Hidden Language of Computer Hardware too Software to larn to a greater extent than near the history of text encoding, it explains Morse code, Brail, too several others including ASCII.

The base64 is 1 of the oldest encoding scheme, which prevents misuse of information past times encoding into ASCII format. Even though at that topographic point are to a greater extent than advanced encoding too encryption schemes available e.g. MD5 or RSH-SHA, Base64 is the best for uncomplicated encoding needs.




JDK 8 Base64 class provides 3 types of encoder too decoder:
  1. Basic
  2. URL
  3. MIME
The argue for that is the grapheme used inward Basic encoding is non URL rubber or filename e.g. it uses "\" every bit 1 of the encoding character, which is a valid grapheme inward URL too PATH. The URL base64 encoder instead uses - too _ (minus too underscore) to encode a String, which tin thence endure safely attached to a URL. You tin purpose the Base64.getUrlEncoder() method to retrieve a URL base of operations encoder inward Java 8.

Similarly, The MIME encoder generates a Base64 encoded String using the basic alphabets (A-Za-Z0-9) but inward an MIME-friendly format: each business of the output is no longer than 76 characters too ends amongst a railroad vehicle render followed past times a linefeed (\r\n), which is non the instance amongst Basic base64 encoding. You tin purpose the Base64.getMimeEncoder() method to retrieve a MIME Base64 encoder. See Java SE 8 for Really Impatient by Cay S. Horstmann to larn to a greater extent than near basic too MIME base64 encoding inward Java 8.

Now lets some illustration of base64 encoding too decoding inward Java 8



Base64 Basic Encoding Example

As I said before, the Basic encoder uses + too \ along amongst alphabets too digits. In lodge to encode a String inward Base64 using this Encoder follow below steps

- acquire the Basic encder past times calling Base64.getEncoder()
- convert String to byte array, purpose StandardCharSet.UTF_8 instead of "UTF-8" String
- telephone telephone the encodeToString(byte[]), number is your base of operations 64 encoded String

In lodge to decode simply contrary the process, acquire the Decoder, move past times the encoded String, have the byte array too convert it to String using new String(byte[]) constructor, brand certain you lot purpose the same character encoding.

Here is an example:

String master copy = "It's a hugger-mugger that C++ developer are improve than Java"; byte[] bytes = original.getBytes(StandardCharsets.UTF_8); String base64Encoded = Base64.getEncoder().encodeToString(bytes); System.out.println("original text: " + original);  System.out.println("Base64 encoded text: " + base64Encoded);  // Decode byte[] asBytes = Base64.getDecoder().decode(base64Encoded); String base64Decoded = new String(asBytes, StandardCharsets.UTF_8); System.out.println("Base64 decoded text: " + base64Decoded);   Output master copy text: It's a hugger-mugger that C++ developer are improve than Java Base64 encoded text: SXQncyBhIHNlY3JldCB0aGF0IEMrKyBkZXZlbG9wZXIgYXJlIGJldHRlciB0aGFuIEphdmE= Base64 decoded text: It's a hugger-mugger that C++ developer are improve than Java

 at that topographic point was no measure agency inward JDK API itself Base64 Encoding too Decoding Example inward Java 8 too before


Base64 URL Encoding Example

If you lot desire to post base64 encoded6 String every bit business office of URL or purpose it within organisation file path, you lot should purpose this encoder. It uses - too _ (minus too underline) instead of + too / to encode text to base64. The number is a URL rubber String. The steps are same every bit previous, except that this fourth dimension you lot necessitate to telephone telephone the Base64.getUrlEncoder() method to retrieve the URL encoder.

Here is an illustration of how to purpose Base64 URL encoder too how it's unlike from Basic encoder:

// Base64 encoding using URL encoder String basicEncoded = Base64.getEncoder() .encodeToString("JavaOrScala?".getBytes(StandardCharsets.UTF_8)); System.out.println("Using Basic encoding: " + basicEncoded);  String urlEncoded = Base64.getUrlEncoder() .encodeToString("JavaOrScala?".getBytes(StandardCharsets.UTF_8)); System.out.println("Using URL encoding: " + urlEncoded);  Output Using Basic encoding: SmF2YU9yU2NhbGE/ Using URL encoding: SmF2YU9yU2NhbGE_

You tin encounter that inward URL encoder, forrad slash(/) is replaced amongst _ (underscore). Now for decoding, you lot tin simply follow the steps given inward the previous illustration using getUrlDecoder() method. See Java SE8 for Programmers (3rd Edition) past times Deitel too Deitel for to a greater extent than examples on base64 encoding too decoding inward Java 8.

 at that topographic point was no measure agency inward JDK API itself Base64 Encoding too Decoding Example inward Java 8 too before




MIME URL Encoding Example
The tertiary type of Base64 encoder provided past times JDK 8 is used to encode MIME content, where each business is non to a greater extent than than 76 grapheme too ends with \r\n. You tin obtain a MIME type of Base64 encoder using getMimeEncoder() method every bit shown inward the next example:

// Base64 encoding using MIME encoder String text = "Best Credit Card for Student is something which                  hand maximum rebate to Student" + "when they buy books, courses too other stationary items"; String mimeEndoded = Base64.getMimeEncoder()                         .encodeToString(text.getBytes(StandardCharsets.UTF_8)); System.out.println("original string: " + text); System.out.println("base65 encoded using MIME encoder: "); System.out.println(mimeEndoded);  // Base64 decoding byte[] decodedBytes = Base64.getMimeDecoder().decode(mimeEndoded); String mimeDecoded = new String(decodedBytes, StandardCharsets.UTF_8); System.out.println("MIME decoded String: " + mimeDecoded);  Output base65 encoded using MIME encoder:  QmVzdCBDcmVkaXQgQ2FyZCBmb3IgU3R1ZGVudCBpcyBzb21ldGhpbmcgd2hpY2ggZ2l2ZSBtYXhp bXVtIHJlYmF0ZSB0byBTdHVkZW50d2hlbiB0aGV5IHB1cmNoYXNlIGJvb2tzLCBjb3Vyc2VzIGFu ZCBvdGhlciBzdGF0aW9uYXJ5IGl0ZW1z MIME decoded String: Best Credit Card for Student is something  which hand maximum rebate to Studentwhen they buy books, courses too  other stationary items

You tin encounter inward Base64 encoded text, each business is lxx characters long because nosotros accept used the MIME Base64 encoder.



Important points

Based on my sense inward Java, next are some worth remembering betoken near Base64 encoding too decoding:

1) Use Apache Commons' Codec's Base64.encodeBase64() too Base64.decodeBase64() prior to Java half-dozen for encoding a String inward base64 too decoding.

2) Don't purpose Sun's sun.misc.BASE64Encoder too sun.misc.BASE64Decoder every bit they are Sun's internal classes too tin endure removed without whatever notice. They are besides solely available on Oracle or Sunday JDK, you lot won't acquire them inward other JVM. Though, they are withal lurking simply about fifty-fifty inward Java 8 :-)

3) The departure betwixt Basic too URL Base64 encoder is that afterward is URL safe. It uses - too _ instead of / too + to encode String which tin endure used inward URL safely. If you lot know forrad slash (/) has a unlike pregnant inward URL.

4) The MIME Base64 Encoder generate output which is no longer 76 characters too ends amongst \r\n

5) In Java 6, you lot tin purpose besides purpose JAXB's DatatypeConverter for encoding a String into base64 inward Java e.g. past times using method printBase64Binary(byte[]) of javax.xml.bind.DatatypeConverter class.

6) Make certain you lot purpose the same type of Base64 decoder e.g. Basic, URL or MIME which you lot accept used spell encoding. Using a unlike type of encoder volition number inward fault or wrong output.



Java Program to Base64 Encoding too Decoding String

Here is our consummate Java plan to demonstrate the use of all 3 types of Base64 encoder inward Java 8. You tin run this illustration to acquire to a greater extent than sense of how Base64 encoding plant inward Java 8:

package test;  import java.nio.charset.StandardCharsets; import java.util.Base64;  /**  * Java Program to present how to base64 encode too decode text inward Java 8. It besides  * shows purpose of unlike types of Base64 encoder inward Java  */ public class Base64Demo {    public static void main(String[] args) {      // Base64 encoding too decoding inward Java 8     // let's purpose Basic encoding first      // Encode     String master copy = "It's a hugger-mugger that C++ developer are improve than Java";     byte[] bytes = original.getBytes(StandardCharsets.UTF_8);     String base64Encoded = Base64.getEncoder().encodeToString(bytes);     System.out.println("original text: " + original);     System.out.println("Base64 encoded text: " + base64Encoded);      // Decode     byte[] asBytes = Base64.getDecoder().decode(base64Encoded);     String base64Decoded = new String(asBytes, StandardCharsets.UTF_8);     System.out.println("Base64 decoded text: " + base64Decoded);      // Base64 encoding using URL encoder     String basicEncoded = Base64.getEncoder().encodeToString(         "JavaOrScala?".getBytes(StandardCharsets.UTF_8));     System.out.println("Using Basic encoding: " + basicEncoded);      String urlEncoded = Base64.getUrlEncoder().encodeToString(         "JavaOrScala?".getBytes(StandardCharsets.UTF_8));     System.out.println("Using URL encoding: " + urlEncoded);      // Base64 encoding using MIME encoder     String text = "Best Credit Card for Student is something which hand maximum rebate to Student"         + "when they buy books, courses too other stationary items";     String mimeEndoded = Base64.getMimeEncoder().encodeToString(         text.getBytes(StandardCharsets.UTF_8));     System.out.println("original string: " + text);     System.out.println("base65 encoded using MIME encoder: ");     System.out.println(mimeEndoded);      // Base64 decoding     byte[] decodedBytes = Base64.getMimeDecoder().decode(mimeEndoded);     String mimeDecoded = new String(decodedBytes, StandardCharsets.UTF_8);     System.out.println("MIME decoded String: " + mimeDecoded);   }  }


That's all near how to encode too decode a String inward base64 inward Java half-dozen too 8. We accept discussed several options for Base64 encoding depending upon the Java version you lot are running, though the measure agency is to purpose the JDK 8 Base64 class from Java 8 onward. It is besides to a greater extent than characteristic rich too provides Basic, URL too MIME Base64 encoder too decoder. It's besides faster than Sunday too Apache's encoder for most of the input. In Java 6, you lot tin besides purpose JAXB's DatatypeConverter for base64 encoding.

Other Java tutorials you lot may similar to explore
  • How to acquire the default grapheme encoding inward Java? (answer)
  • How to base of operations 64 encode too decode using Apache Commons Codec? (tutorial)
  • Difference betwixt UTF-8, UTF-16, too UTF-32 encoding? (answer)
  • Difference betwixt URL rewriting too URL encoding inward Servlet? (answer)
  • How to convert byte array to String inward Java? (example)
  • How to generate MD5 hash inward Java? (tutorial)
  • 10 Articles Every Programmer Should Read (article)


Further Learning
Data Structures too Algorithms: Deep Dive Using Java
Java Fundamentals: The Java Language
Complete Java Masterclass


No comments:

Post a Comment