Check if String is Base64 Encoded – 检查字符串是否为 Base64 编码

最后修改: 2024年 2月 24日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.简介</span

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.

在 Java 编程中,我们经常使用数据编码和解码。此外,Base64 编码非常流行,用于将二进制数据转换为ASCII文本格式。

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

在本教程中,我们将发现可用于验证给定字符串是否在 Java 中进行了 base64 编码的技术。

2. Understanding Base64 Encoding

2.了解 Base64 编码 .

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

Base64 是一种二进制到文本的编码方案,可将二进制数据编码为 ASCII 字符串格式。

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

每组 3 个字节对应 4 个字符,由于数据将通过文本协议发送,因此通信过程非常安全。

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

3.使用 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.

Java 在 java.util 包。此外,使用最多的类是 Base64类,它是 Java 8. 的一部分。

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

让我们 演示如何使用 Base64 类来检查字符串是否为 Base64 编码:

@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.

此测试函数应用Base64.getDecoder.decode() 方法解码 Base64 编码字符串 SGVsbG8gd29ybGQ.

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

如果成功,则断言assertTrue(true)表明字符串是 Base64 编码。 如果出现意外异常(捕获IllegalArgumentException),则测试失败。测试失败。

@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!.

与前一个测试方法相同,这个 应用 Base64.getDecoder.decode() 方法对非 Base64 编码字符串 Hello World 进行解码!.

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

如果测试抛出预期的(IllegalArgumentException)、测试断言assertTrue(true) 。否则,测试失败。 (true) 否则,测试失败。

4. Using Regular Expressions

4.使用正则表达式 4.

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.

另一方面,基于正则表达式的方法也可用于 Base64 编码验证。简单地说,我们可以使用一个模式并将其与所需的字符串进行匹配。

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.

在此测试方法中,我们使用 The Pattern.compile()方法来确保给定字符串符合 Base64 编码格式。然后,我们创建一个 Matcher对象,用于将输入字符串与定义的模式相匹配。

5. Conclusion

5.结论

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. 

总之,本文深入探讨了 Base64 编码验证的几种方法,如 Base64.getDecoder().() 和 regex,其总体目的是为 Java 中的验证写入器编码系统建立灵活性。

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

一如既往,示例的源代码可从 GitHub 上获取。