0% found this document useful (0 votes)
1 views28 pages

Base64 Encoding and Decoding in Java

The document explains Base64 encoding and decoding in Java, detailing the use of the Base64 class for encrypting and decrypting data, as well as providing methods for basic encoding and decoding. It includes examples of encoding and decoding strings and URLs, along with the Java forEach loop for iterating over collections. Additionally, it introduces the forEachOrdered method for maintaining order during iteration.

Uploaded by

shrey16211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views28 pages

Base64 Encoding and Decoding in Java

The document explains Base64 encoding and decoding in Java, detailing the use of the Base64 class for encrypting and decrypting data, as well as providing methods for basic encoding and decoding. It includes examples of encoding and decoding strings and URLs, along with the Java forEach loop for iterating over collections. Additionally, it introduces the forEachOrdered method for maintaining order during iteration.

Uploaded by

shrey16211
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Base64 Encoding and Decoding in Java

• Java provides a class Base64 to deal with


encryption. You can encrypt and decrypt your data
by using provided methods.
• Base 64 is an encoding scheme that converts binary data
into text format so that encoded textual data can be easily
transported over network un-corrupted and without any
data loss.
• need to import java.util.Base64 in your source file
to use its methods.
• class provides three different encoders and
decoders to encrypt information at each level.
Basic Encoding and Decoding
• uses the Base64 alphabet specified by Java in RFC 4648 and RFC
2045 for encoding and decoding operations.
• Encoder does not add any line separator character.
• decoder rejects data that contains characters outside the base64
alphabet.

URL and Filename Encoding and


Decoding
• uses the Base64 alphabet specified by Java in RFC 4648 for
encoding and decoding operations.
Nested Classes of Base64
• Base64.Decode: This class implements a decoder for decoding byte
data using the Base64 encoding scheme as specified in RFC 4648
and RFC 2045.

• Base64.Encoder: This class implements an encoder for encoding


byte data using the Base64 encoding scheme as specified in RFC
4648 and RFC 2045.
Base64 Methods
• public static Base64.Decoder getDecoder()
returns a Base64.Decoder that decodes using the Basic type base64
encoding scheme.
• public static Base64.Encoder getEncoder()
returns a Base64.Encoder that encodes using the Basic type base64
encoding scheme.
• public static Base64.Decoder getUrlDecoder()
It returns a Base64.Decoder that decodes using the URL and Filename
safe type base64 encoding scheme.
• public static Base64.Decoder getMimeDecoder()
returns a Base64.Decoder that decodes using the MIME (Multipurpose Internet
Mail Extensions) type base64 decoding scheme.
Base64.Decoder Methods
• public byte[] decode(byte[] src)
decodes all bytes from the input byte array using the Base64 encoding
scheme, writing the results into a newly-allocated output byte array.
The returned byte array is of the length of the resulting bytes.

• public byte[] decode(String src)


decodes a Base64 encoded String into a newly-allocated byte array
using the Base64 encoding scheme.
• public int decode(byte[] src, byte[] dst)
decodes all bytes from the input byte array using the Base64 encoding
scheme, writing the results into the given output byte array, starting at
offset 0.
• public ByteBuffer decode(ByteBuffer buffer)
decodes all bytes from the input byte buffer using the Base64 encoding scheme,
writing the results into a newly-allocated ByteBuffer.

• public InputStream wrap(InputStream is)


returns an input stream for decoding Base64 encoded byte stream.
Base64.Encoder Methods
• public byte[] encode(byte[] src)
encodes all bytes from the specified byte array into a newly-allocated
byte array using the Base64 encoding scheme. The returned byte array
is of the length of the resulting bytes
• public int encode(byte[] src, byte[] dst)
encodes all bytes from the specified byte array using the Base64 encoding
scheme, writing the resulting bytes to the given output byte array, starting at
offset 0.
• public String encodeToString(byte[] src)
encodes the specified byte array into a String using the Base64 encoding
scheme.
• public ByteBuffer encode(ByteBuffer buffer)
encodes all remaining bytes from the specified byte buffer into a newly-
allocated ByteBuffer using the Base64 encoding scheme.
• public OutputStream wrap(OutputStream os)
wraps an output stream for encoding byte data using the Base64
encoding scheme
• public Base64.Encoder withoutPadding()
returns an encoder instance that encodes equivalently to this one, but
without adding any padding character at the end of the encoded byte
data.
Java Base64 Example: Basic Encoding and
Decoding
// Java program to demonstrate
// Encoding simple String into Basic Base 64 format
import java.util.*;
public class GFG {
public static void main(String[] args){
// create a sample String to encode
String sample = "India Team will win the Cup";
// print actual String
System.out.println("Sample String:\n“ + sample);
// Encode into Base64 format
String BasicBase64format =
Base64.getEncoder().encodeToString(sample.getBytes());
// print encoded String
System.out.println("Encoded String:\n"+ BasicBase64format);
}
}
• Output
• Sample String:
• India Team will win the Cup
• Encoded String:
• SW5kaWEgVGVhbSB3aWxsIHdpbiB0aGUgQ3Vw
• Program 2: Decode Basic Base 64 format to String
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create an encoded String to decode
String encoded ="SW5kaWEgVGVhbSB3aWxsIHdpbiB0aGUgQ3Vw";
// print encoded String
System.out.println("Encoded String:\n" + encoded);
// decode into String from encoded format
byte[] actualByte = Base64.getDecoder() .decode(encoded);
String actualString = new String(actualByte);
// print actual String
System.out.println("actual String:\n"+ actualString);
}
}
Output:
Encoded String:
SW5kaWEgVGVhbSB3aWxsIHdpbiB0aGUgQ3Vw
actual String:
India Team will win the Cup
Example: URL encoding using Base64 class.
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create a sample url String to encode
String sampleURL = "https:// www.google.com/";
// print actual URL String
System.out.println("Sample URL:\n"+ sampleURL);
// Encode into Base64 URL format
String encodedURL =
Base64.getUrlEncoder().encodeToString(sampleURL.getBytes());
// print encoded URL
System.out.println("encoded URL:\n" + encodedURL);
}
}

Output:
Sample URL:
https:/ / www.google.com /
encoded URL:
aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv
Example: URL Decoding using Base64 class.
import java.util.*;
public class GFG {
public static void main(String[] args)
{ // create a encoded URL to decode
String encoded ="aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv";
System.out.println("encoded URL:\n" + encoded);
// decode into String URL from encoded format
byte[] actualByte = Base64.getUrlDecoder() .decode(encoded);
String actualURLString = new String(actualByte);
// print actual String
System.out.println("actual String:\n" + actualURLString); }}
Output:
encoded URL:
aHR0cHM6Ly93d3cuZ2Vla3Nmb3JnZWVrcy5vcmcv
actual String:
https://www.google.com/
Java forEach loop
• Java provides a new method forEach() to iterate the elements.
• defined in Iterable and Stream interface.
• It is a default method defined in the Iterable interface.
• Collection classes which extends Iterable interface can use
forEach loop to iterate elements.

• This method takes a single parameter which is a functional


interface. So, you can pass lambda expression as an argument.
• forEach() Signature in Iterable Interface
default void forEach(Consumer<super T>action)

• Java 8 forEach() example


import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing lambda expression------
--------");
gamesList.forEach(games -> System.out.println(games));

}
}

Output:
------------Iterating by passing lambda expression--------------
Football
Cricket
Chess
Hocky
Java 8 forEach() example 2
import java.util.ArrayList;
import java.util.List;
public class ForEachExample {
public static void main(String[] args) {
List<String> gamesList = new ArrayList<String>();
gamesList.add("Football");
gamesList.add("Cricket");
gamesList.add("Chess");
gamesList.add("Hocky");
System.out.println("------------Iterating by passing method reference---------------");
gamesList.forEach(System.out::println);
}
}
Output:

------------Iterating by passing method reference---------------


Football
Cricket
Chess
Hocky
Java Stream forEachOrdered() Method
• with forEach() method, Java provides one more
method forEachOrdered(). It is used to iterate
elements in the order specified by the stream.

• Singnature:
void forEachOrdered(Consumer<? super T> action)
forEachOrdered() Method Example
1.import java.util.ArrayList;
2.import java.util.List;
3.public class ForEachOrderedExample {
4. public static void main(String[] args) {
5. List<String> gamesList = new ArrayList<Str
ing>();
6. gamesList.add("Football");
7. gamesList.add("Cricket");
1. gamesList.add("Chess");
2. gamesList.add("Hocky");
3. System.out.println("------------
Iterating by passing lambda expression---------------");
4. gamesList.stream().forEachOrdered(games -
> System.out.println(games));
5. System.out.println("------------
Iterating by passing method reference---------------");
6. gamesList.stream().forEachOrdered(System.out::println);
7. }
8.
9.}
------------Iterating by passing lambda expression---------------
Football
Cricket
Chess
Hocky
------------Iterating by passing method reference---------------
Football
Cricket
Chess
Hocky
Thank You

You might also like