Encoding and decoding using BASE64

Directory of series articles

SpringBoot integrates RabbitMQ and implements message sending and receiving
Parse JSON format parameters & modify the key of the object
VUE integrates Echarts to achieve simple data visualization
Using BigDecimal in Java to perform operations such as addition, subtraction, multiplication, and division on string values
List<HashMap<String,String>>implement custom string sorting (key sorting, value sorting)

For more articles in this series, please check my homepage

Article directory

  • Table of Contents of Series Articles
  • Preface
  • 1. Data preparation
  • 2. Scenario analysis
  • 3. BASE64 encoding
    • 3.1 Code
    • 3.2 Renderings
  • 4. BASE64 decoding
    • 4.1 Code
    • 4.2 Renderings
  • Summarize

Foreword

BASE64 encoding is an encoding method that converts binary data into ASCII characters. It is often used to transmit and save binary data during network transmission. BASE64 encoding can convert any binary data into text string form. Due to its special encoding method, it is not easy to be directly recognized by humans and is also relatively difficult to be tampered with.

The Java language provides support for BASE64 encoding and decoding, which makes encoding and decoding operations easy. Encoding/decoding with BASE64 is very simple, just call the corresponding encoder or decoder. When performing BASE64 encoding and decoding, you need to pay attention to data type conversion and the processing of some special characters.

Below we will introduce how to perform BASE64 encoding and decoding operations in Java, as well as some attention points and example demonstrations to help everyone better master this knowledge point.

1. Data preparation

In the preface, we also learned that BASE64 encoding is mainly used in network transmission, which makes it difficult to be directly recognized by people and more difficult to be tampered with. Therefore, we generally use encoding when sending json data to prevent it from being discovered by others.

Next we will prepare a json data, as shown below:

{<!-- -->
  "status": "success",
  "data": {<!-- -->
    "users": [
      {<!-- -->
        "id": 1,
        "name": "John Doe",
        "age": 30,
        "email": "[email protected]"
      },
      {<!-- -->
        "id": 2,
        "name": "Jane Smith",
        "age": 25,
        "email": "[email protected]"
      }
    ],
    "products": [
      {<!-- -->
        "id": 1001,
        "name": "Product A",
        "price": 19.99
      },
      {<!-- -->
        "id": 1002,
        "name": "Product B",
        "price": 29.99
      }
    ]
  },
  "message": "Data retrieved successfully"
}

If this data is important, we must encode it before transmission to make the data more secure for transmission.

2. Scenario analysis

BASE64 encoding is widely used in many scenarios. The following is an analysis of some common scenarios:

  1. Data transmission: In network communication, some data may contain special characters or cannot be transmitted directly. In this case, the data can be BASE64 encoded and transmitted in text form. The receiving end then decodes the data and restores it to its original format.
  2. Image and file transfer: In web development, the transfer of images and files is often involved. Since the HTTP protocol only supports text transmission, the binary image or file needs to be BASE64-encoded and then embedded into the web page or API request in text form.
  3. Data storage: Some databases or systems only support text type storage and cannot directly store binary data. In this case, the binary data can be BASE64-encoded and stored in a database or other storage medium.
  4. Key exchange: In encryption algorithms, the transmission and storage of keys need to ensure security. Use BASE64 encoding to convert the key from binary to text form for easier transmission and storage.

It should be noted that although BASE64 encoding can ensure the reliability of data transmission, it is not an encryption algorithm and cannot provide data security. Therefore, in scenarios involving sensitive information, it is still necessary to combine other encryption methods to ensure data security.

3. BASE64 encoding

3.1 Code

Through the above description, everyone should have a certain understanding of BASE64. Let’s use java code to implement BASE64 encoding and encode the above json string:

 //Encoding: encode: Get the bytes of the string and then encode it jsonObject.getBytes()
        byte[] encodedBytes = java.util.Base64.getEncoder().encode(jsonObject.getBytes());
        String base64Str = new String(encodedBytes);
        System.out.println("This is the encoded base64 string:" + base64Str);

The specific explanation is as follows:

  1. byte[] encodedBytes = java.util.Base64.getEncoder().encode(jsonObject.getBytes());: First, convert the jsonObject object into a byte array, And use java.util.Base64.getEncoder() to obtain the BASE64 encoder, and then encode the byte array to obtain the encoded byte array encodedBytes.
  2. String base64Str = new String(encodedBytes);: Convert the encoded byte array encodedBytes into string form, that is, obtain the BASE64-encoded string base64Str.
  3. System.out.println(“This is the encoded base64 string:” + base64Str);: Print out the encoded BASE64 string.

Summary: This code snippet implements BASE64 encoding of a JSON object and prints the encoding result as a string.

3.2 Renderings

By encoding the json string with the above code, you can get the encoded string. The running effect is shown in the figure below:

4. BASE64 decoding

4.1 Code

After encoding, we can transmit it, but after receiving the json data, the user needs to decode it and store or process it in the database, so here we write the decoding code as follows:

 //This conversion to spaces is " + ". When there are spaces, an error (illegal character) will be reported.
        String replace = base64Str.replace(" ", " + ");
        byte[] basebyte = java.util.Base64.getDecoder().decode(replace);
        String utf8Str = new String(basebyte, "utf-8");
        System.out.println("This is the decoded utf-8 string:" + utf8Str);

The main function of this code is to replace the spaces in a Base64-encoded string with ” + ” signs, then perform Base64 decoding, and finally convert the decoded byte array into a UTF-8 format string and output it. .

  1. Use the **replace()** method to replace spaces with ” + ” signs. The regular expression “” is used here to match spaces, because in Java’s string operations, spaces are a special character and need to be matched using regular expressions.
  2. Use the **java.util.Base64.getDecoder().decode()** method to decode the replaced Base64 encoded string. The decoded result is a byte array.
  3. Use the **new String(basebyte, “utf-8”)** method to convert the decoded byte array into a UTF-8 format string.
  4. Output the decoded string.

It should be noted that this code uses Java's Base64 class for Base64 encoding and decoding. When decoding using the Base64.getDecoder().decode() method, the decoded result is a byte array. If you need to convert it to a string, you need to use the constructor of the String class, such as new String(basebyte, " utf-8").

4.2 Renderings

By decoding the above code, you can restore the json string before encoding. The rendering is as follows:

Note: When converting from byte array to String type, garbled characters will appear if UTF-8 is not added.

Summary

The advantage of Base64 encoding is that it has good readability, can be easily read and transmitted, and can encrypt data to prevent data leakage. However, since the encoded length of Base64 encoding is longer than the original data length, it may cause slower transfer speeds. In addition, Base64 encoding can only encrypt the bits of the original data, but not the value of the original data.

In Java, you can use the java.util.Base64 class for Base64 encoding and decoding. Commonly used methods include:

  1. encode() method: Convert the original data to a Base64 encoded string.
  2. getEncoder() method: Gets a Base64 encoder for converting data into a Base64-encoded string.
  3. decode() method: Convert Base64 encoded string to original data.
  4. getDecoder() method: Gets a Base64 decoder for converting Base64-encoded strings into raw data.

When using Base64 encoding and decoding, you need to pay attention to the type of original data (such as byte array, string, etc.) and the choice of encoder.