Table of Contents
Introduction
JAVA’s support for base64
Classification and implementation of Base64 in JDK
Home Java javaTutorial How to implement base64 encoder in Java

How to implement base64 encoder in Java

Apr 28, 2023 pm 04:04 PM
java base64

Introduction

What is Base64 encoding? Before answering this question, we need to understand the classification of files in computers. For computers, files can be divided into two categories, one is text files and the other is binary files.

For binary files, their content is represented in binary, which is not immediately understandable to humans. If you try to open a binary file with a text editor, you may see gibberish. This is because the encoding method of binary files is different from the encoding method of text files, so when the text editor tries to translate the binary files into text content, garbled characters will appear.

For text files, there are many encoding methods, such as the earliest ASCII encoding and the currently commonly used encoding methods such as UTF-8 and UTF-16. Even text files may see garbled characters if you open them using a different encoding.

So whether it is a text file or a binary file, the encoding format needs to be unified. In other words, what the encoding of writing looks like, then the encoding of data reading should also match it.

Base64 encoding is actually an encoding method that encodes binary data into visual ASCII characters.

Why is there such a requirement?

We know that the development of the computer world does not happen overnight. It is a process of slow growth. For character encoding, it only supports ASCII encoding at first, and later it was expanded to Unicode and so on. Therefore, for many applications, encoding formats other than ASCII encoding are not supported. So how to display non-ASCII code in these systems?

The solution is to perform encoding mapping to map non-ASCII characters to ASCII characters. Base64 is such an encoding method.

The common place to use Base64 is in web pages. Sometimes we need to display images on web pages, so we can base64 encode the images and then fill them into html.

Another application is to base64 encode the file and then send it as an email attachment.

JAVA’s support for base64

Since base64 encoding is so easy to use, let’s take a look at the base64 implementation in JAVA.

There is a corresponding base64 implementation in java, called java.util.Base64. This class is a tool class for Base64, which was introduced by JDK in version 1.8.

Base64 provides three getEncoder and getDecoder methods. By obtaining the corresponding Encoder and Decoder, you can then call the encoder's encode and decode methods to encode and decode the data, which is very convenient.

Let’s first take a look at the basic usage examples of Base64:

1

2

3

4

5

6

7

8

// 使用encoder进行编码

String encodedString = Base64.getEncoder().encodeToString("what is your name baby?".getBytes("utf-8"));

System.out.println("Base64编码过后的字符串 :" + encodedString);

 

// 使用encoder进行解码

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);

 

System.out.println("解码过后的字符串: " + new String(decodedBytes, "utf-8"));

Copy after login

As a tool class, the Base64 tool class provided in the JDK is still very useful.

I won’t explain its use in detail here. This article mainly analyzes how Base64 is implemented in JDK.

Classification and implementation of Base64 in JDK

The Base64 class in JDK provides three encoder methods, namely getEncoder, getUrlEncoder and getMimeEncoder:

1

2

3

4

5

6

7

8

9

10

11

public static Encoder getEncoder() {

     return Encoder.RFC4648;

}

 

public static Encoder getUrlEncoder() {

     return Encoder.RFC4648_URLSAFE;

}

 

public static Encoder getMimeEncoder() {

    return Encoder.RFC2045;

}

Copy after login

Similarly, it Three corresponding decoder are also provided, namely getDecoder, getUrlDecoder, getMimeDecoder:

1

2

3

4

5

6

7

8

9

10

11

public static Decoder getDecoder() {

     return Decoder.RFC4648;

}

 

public static Decoder getUrlDecoder() {

     return Decoder.RFC4648_URLSAFE;

}

 

public static Decoder getMimeDecoder() {

     return Decoder.RFC2045;

}

Copy after login

As can be seen from the code, these three encodings correspond to RFC4648, RFC4648_URLSAFE and RFC2045 respectively.

These three are variants of base64 encoding. Let’s take a look at their differences:

##RFC 4648: base64url (URL- and filename-safe standard)
Encoding nameEncoded characters Encoded charactersEncoded characters
The 62nd digitThe 63rd digitComplete character
RFC 2045: Base64 transfer encoding for MIME / = mandatory
RFC 4648: base64 (standard) /= optional
-_= optional
You can see that the difference between base64 and Base64url is that the 62nd and 63rd encoded characters are different, and the difference between base64 for MIME and base64 is whether the completion character is mandatory.

In addition, for Basic and base64url, line separator characters will not be added, while base64 for MIME will add '\r' and '\n' as line separators after a line exceeds 76 characters.

Finally, if during the decoding process, characters that are not found in the Base64 mapping table are processed differently, base64 and Base64url will be rejected directly, while base64 for MIME will be ignored.

The difference between base64 and Base64url can be seen through the following two methods:

1

2

3

4

5

6

7

private static final char[] toBase64 = {

    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',

    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',

    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',

    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',

    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'

};

Copy after login

1

2

3

4

5

6

7

private static final char[] toBase64URL = {

    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',

    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',

    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',

    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',

    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'

};

Copy after login

For MIME, the maximum number of characters in a line and the newline character are defined:

1

2

private static final int MIMELINEMAX = 76;

private static final byte[] CRLF = new byte[] {'\r', '\n'};

Copy after login

Advanced usage of Base64

Generally, the length of the object we encode with Base64 is fixed. We only need to convert the input object into a byte array to call the encode or decode method.

But in some cases we need to convert stream data. At this time, we can use the two methods of wrapping Stream provided in Base64:

1

2

3

4

5

public OutputStream wrap(OutputStream os) {

    Objects.requireNonNull(os);

    return new EncOutputStream(os, isURL ? toBase64URL : toBase64,

                               newline, linemax, doPadding);

}

Copy after login

1

2

3

4

public InputStream wrap(InputStream is) {

    Objects.requireNonNull(is);

    return new DecInputStream(is, isURL ? fromBase64URL : fromBase64, isMIME);

}

Copy after login
These two methods are respectively Corresponds to encoder and decoder.

The above is the detailed content of How to implement base64 encoder in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles