Base64 Encoding together with Decoding Example inward Java viii together with before

Though, in that location are a twosome of ways to Base64 encode a String inwards Java e.g. yesteryear using Java 6's javax.xml.bind.DatatypeConverter#printBase64Binary(byte[]) or yesteryear using Apache Commons Codec's Base64.encodeBase64(byte[) together with Base64.decodeBase64(byte[])as shown here, or the infamous Sun's internal base64 encoder together with decoder, sun.misc.BASE64Encoder().encode() together with sun.misc.BASE64Decoder().decode(), in that location was no measure agency inwards JDK API itself. That was i of the few missing exceptional (another i is close joining string) which is addressed inwards Java 8. The JDK 8 API contains a Base64 cast inwards java.util packet which supports both encoding together with decoding text inwards Base64. You tin utilisation Base64.Encoder to encode a byte array or String together with Base64.Decoder to decode a base64 encoded byte array or String inwards Java 8.

The JDK 8 API equally good provides dissimilar types of Base64 encoder e.g. basic, URL together with MIME to back upwards dissimilar needs. I'll say you lot what is the divergence betwixt Basic, URL together with MIME Base64 encoder together with why you lot necessitate inwards 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 supersede each grapheme inwards master copy String inwards an algorithmic agency thence that it tin live on decoded later. The procedure which converts master copy String to something else is known equally encoding together with the opposite procedure to convert an encoded String to master copy content is known equally decoding.

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

The base64 is i of the oldest encoding scheme, which prevents misuse of information yesteryear encoding into ASCII format. Even though in that location are to a greater extent than advanced encoding together with encryption schemes available e.g. MD5 or RSH-SHA, Base64 is the best for uncomplicated encoding needs.



JDK 8 Base64 cast provides iii types of encoder together with decoder:
  1. Basic
  2. URL
  3. MIME
The argue for that is the grapheme used inwards Basic encoding is non URL rubber or filename e.g. it uses "\" equally i of the encoding character, which is a valid grapheme inwards URL together with PATH. The URL base64 encoder instead uses - together with _ (minus together with underscore) to encode a String, which tin together with then live on safely attached to a URL. You tin utilisation the Base64.getUrlEncoder() method to retrieve a URL base of operations encoder inwards Java 8.

Similarly, The MIME encoder generates a Base64 encoded String using the basic alphabets (A-Za-Z0-9) but inwards an MIME-friendly format: each trouble of the output is no longer than 76 characters together with ends amongst a railroad vehicle render followed yesteryear a linefeed (\r\n), which is non the illustration amongst Basic base64 encoding. You tin utilisation the Base64.getMimeEncoder() method to retrieve a MIME Base64 encoder. See Java SE 8 for Really Impatient by Cay S. Horstmann to acquire to a greater extent than close basic together with MIME base64 encoding inwards Java 8.

Now lets some illustration of base64 encoding together with decoding inwards Java 8



Base64 Basic Encoding Example

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

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

In club to decode simply opposite the process, acquire the Decoder, transcend the encoded String, have the byte array together with convert it to String using new String(byte[]) constructor, brand certain you lot utilisation the same character encoding.

Here is an example:

String master copy = "It's a hugger-mugger that C++ developer are amend 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 amend than Java Base64 encoded text: SXQncyBhIHNlY3JldCB0aGF0IEMrKyBkZXZlbG9wZXIgYXJlIGJldHRlciB0aGFuIEphdmE= Base64 decoded text: It's a hugger-mugger that C++ developer are amend than Java

 in that location was no measure agency inwards JDK API itself Base64 Encoding together with Decoding Example inwards Java 8 together with before


Base64 URL Encoding Example

If you lot desire to post base64 encoded6 String equally utilisation of URL or utilisation it within organization file path, you lot should utilisation this encoder. It uses - together with _ (minus together with underline) instead of + together with / to encode text to base64. The result is a URL rubber String. The steps are same equally previous, except that this fourth dimension you lot necessitate to telephone phone the Base64.getUrlEncoder() method to retrieve the URL encoder.

Here is an illustration of how to utilisation Base64 URL encoder together with how it's dissimilar 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 come across that inwards URL encoder, forrard slash(/) is replaced amongst _ (underscore). Now for decoding, you lot tin simply follow the steps given inwards the previous illustration using getUrlDecoder() method. See Java SE8 for Programmers (3rd Edition) yesteryear Deitel together with Deitel for to a greater extent than examples on base64 encoding together with decoding inwards Java 8.

 in that location was no measure agency inwards JDK API itself Base64 Encoding together with Decoding Example inwards Java 8 together with before




MIME URL Encoding Example
The 3rd type of Base64 encoder provided yesteryear JDK 8 is used to encode MIME content, where each trouble is non to a greater extent than than 76 grapheme together with ends with \r\n. You tin obtain a MIME type of Base64 encoder using getMimeEncoder() method equally shown inwards the next example:

// Base64 encoding using MIME encoder String text = "Best Credit Card for Student is something which                  plough over maximum rebate to Student" + "when they buy books, courses together with 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 plough over maximum rebate to Studentwhen they buy books, courses together with  other stationary items

You tin come across inwards Base64 encoded text, each trouble is lxx characters long because nosotros convey used the MIME Base64 encoder.



Important points

Based on my sense inwards Java, next are some worth remembering betoken close Base64 encoding together with decoding:

1) Use Apache Commons' Codec's Base64.encodeBase64() together with Base64.decodeBase64() prior to Java vi for encoding a String inwards base64 together with decoding.

2) Don't utilisation Sun's sun.misc.BASE64Encoder together with sun.misc.BASE64Decoder equally they are Sun's internal classes together with tin live on removed without whatsoever notice. They are equally good exclusively available on Oracle or Dominicus JDK, you lot won't acquire them inwards other JVM. Though, they are yet lurking unopen to fifty-fifty inwards Java 8 :-)

3) The divergence betwixt Basic together with URL Base64 encoder is that afterward is URL safe. It uses - together with _ instead of / together with + to encode String which tin live on used inwards URL safely. If you lot know forrard slash (/) has a dissimilar important inwards URL.

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

5) In Java 6, you lot tin utilisation equally good utilisation JAXB's DatatypeConverter for encoding a String into base64 inwards Java e.g. yesteryear using method printBase64Binary(byte[]) of javax.xml.bind.DatatypeConverter class.

6) Make certain you lot utilisation the same type of Base64 decoder e.g. Basic, URL or MIME which you lot convey used acre encoding. Using a dissimilar type of encoder volition result inwards mistake or wrong output.



Java Program to Base64 Encoding together with Decoding String

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

package test;  import java.nio.charset.StandardCharsets; import java.util.Base64;  /**  * Java Program to exhibit how to base64 encode together with decode text inwards Java 8. It equally good  * shows utilisation of dissimilar types of Base64 encoder inwards Java  */ public class Base64Demo {    public static void main(String[] args) {      // Base64 encoding together with decoding inwards Java 8     // let's utilisation Basic encoding first      // Encode     String master copy = "It's a hugger-mugger that C++ developer are amend 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 plough over maximum rebate to Student"         + "when they buy books, courses together with 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 close how to encode together with decode a String inwards base64 inwards Java vi together with 8. We convey discussed several options for Base64 encoding depending upon the Java version you lot are running, though the measure agency is to utilisation the JDK 8 Base64 cast from Java 8 onward. It is equally good to a greater extent than characteristic rich together with provides Basic, URL together with MIME Base64 encoder together with decoder. It's equally good faster than Dominicus together with Apache's encoder for most of the input. In Java 6, you lot tin equally good utilisation JAXB's DatatypeConverter for base64 encoding.

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


References
Base64.Encoder inwards Java SE 8
Base64 Encoding


Subscribe to receive free email updates:

0 Response to "Base64 Encoding together with Decoding Example inward Java viii together with before"

Posting Komentar