Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In Java programming, we quite often work with data encoding and decoding. Additionally, Base64 encoding is popular and used to convert binary data into ASCII text format.

In this tutorial, we’ll discover techniques that can be used to verify if the given string is base64 encoded in Java.

2. Understanding Base64 Encoding

Base64 is a binary-to-text encoding scheme that encodes binary data into an ASCII string format.

Every group of 3 bytes corresponds to four characters, making the communication process safe since the data will be sent over textual protocols.

3. Using Base64.getDecoder().decode() 

Java provides libraries for the Base64 encoding and decoding tasks in the java.util package. Moreover, the most used class is the Base64 class, part of Java 8.

Let’s demonstrate how to use the Base64 class to check if a string is Base64 encoded:

@Test
public void givenBase64EncodedString_whenDecoding_thenNoException() {
    try {
        Base64.getDecoder().decode("SGVsbG8gd29ybGQ=");
        assertTrue(true);
    } catch (IllegalArgumentException e) {
        fail("Unexpected exception: " + e.getMessage());
    }
}

This test function applies the Base64.getDecoder.decode() method to decode a Base64 encoded string SGVsbG8gd29ybGQ.

If successful, it asserts assertTrue(true), indicating that the string is Base64 encoded. If an unexpected exception occurs (catching IllegalArgumentException), the test fails.

@Test
public void givenNonBase64String_whenDecoding_thenCatchException() {
    try {
        Base64.getDecoder().decode("Hello world!");
        fail("Expected IllegalArgumentException was not thrown");
    } catch (IllegalArgumentException e) {
        assertTrue(true);
    }
}

Same as the previous test method, this one applies the Base64.getDecoder.decode() method to decode a Non-Base64 encoded string Hello World!.

If the test throws the expected (IllegalArgumentException), the test asserts assertTrue(true). Otherwise, the test fails. 

4. Using Regular Expressions

On the other hand, a regular expression-based approach can also be considered for Base64 encoding verification. Simply, we can use a pattern and match it against the desired string.

Let’s see how we can implement this approach: 

@Test
public void givenString_whenOperatingRegex_thenCheckIfItIsBase64Encoded() {
    Pattern BASE64_PATTERN = Pattern.compile(
      "^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"
    );

    assertTrue(BASE64_PATTERN.matcher("SGVsbG8gd29ybGQ=").matches());
}

In this test method, we define a regular expression Pattern named BASE64_PATTERN using the Pattern.compile() method to make sure a given string conforms to the Base64 encoding format. After that, we create a Matcher object, which is used to match the input string against the defined pattern. If the entire string matches, it returns true; otherwise, it returns false.

5. Conclusion

In summary, this article delves into several methods for Base64 encoding verification, such as Base64.getDecoder().decode() and regex, serving the overall purpose of building flexibility into the system of encoding verification writers in Java. 

As always, the source code for the examples is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.