perf: decode Base64 with bounded lookup-table groups

This commit is contained in:
qaiu committed 2026-11-20 19:37:04 +08:00
1 parent 8c07c6e657
commit 5681d3b805
3 files changed
+103 -30

No files matched your search

+9
View File
@@ -52,6 +52,15 @@ jobs:
- name: Maven 编译打包 - name: Maven 编译打包
run: mvn -B package -DskipTests --file pom.xml run: mvn -B package -DskipTests --file pom.xml
- name: Base64 兼容性回归测试
if: github.event_name == 'pull_request'
run: >-
mvn -B test -DskipTests=false
-Dtest=Base64DecoderTest,HttpProxyBase64Test,Base64CompatibilityTest
-Dsurefire.failIfNoSpecifiedTests=false
-DargLine=-XX:-UseBASE64Intrinsics
--file pom.xml
- name: 更新依赖图谱 - name: 更新依赖图谱
uses: advanced-security/maven-dependency-submission-action@v3 uses: advanced-security/maven-dependency-submission-action@v3
if: github.event_name != 'pull_request' if: github.event_name != 'pull_request'
@@ -1,49 +1,85 @@
package cn.qaiu.util; package cn.qaiu.util;
/** Strict Base64 decoding without the HotSpot Base64 intrinsic (CVE-2026-114938). */ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* Strict Base64 decoding without the HotSpot Base64 intrinsic (CVE-2026-114938).
* Like the JDK's String decoder, this reads ISO-8859-1 bytes.
* Unmappable characters become '?', which is rejected by both alphabets.
*/
public final class Base64Decoder { public final class Base64Decoder {
private static final String BASIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static final byte[] BASIC = alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
private static final String URL_SAFE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; private static final byte[] URL_SAFE = alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
private Base64Decoder() { private Base64Decoder() {
} }
public static byte[] decode(String input) { public static byte[] decode(String input) {
return decode(input, BASIC); return decode(input.getBytes(StandardCharsets.ISO_8859_1), BASIC);
} }
public static byte[] decodeUrl(String input) { public static byte[] decodeUrl(String input) {
return decode(input, URL_SAFE); return decode(input.getBytes(StandardCharsets.ISO_8859_1), URL_SAFE);
} }
private static byte[] decode(String input, String alphabet) { private static byte[] decode(byte[] input, byte[] alphabet) {
int length = input.length(); int length = input.length;
int firstPadding = input.indexOf('='); int dataLength = length;
int dataLength = firstPadding < 0 ? length : firstPadding; if (dataLength > 0 && input[dataLength - 1] == '=') {
dataLength--;
if (dataLength > 0 && input[dataLength - 1] == '=') {
dataLength--;
}
}
int remainder = dataLength % 4; int remainder = dataLength % 4;
if (remainder == 1 || (firstPadding >= 0 int padding = length - dataLength;
&& (remainder == 0 || length % 4 != 0 if (remainder == 1 || (padding != 0 && remainder + padding != 4)) {
|| length - dataLength != 4 - remainder
|| input.charAt(length - 1) != '='))) {
throw new IllegalArgumentException("Invalid Base64 padding or length"); throw new IllegalArgumentException("Invalid Base64 padding or length");
} }
byte[] decoded = new byte[dataLength / 4 * 3 + remainder * 6 / 8]; int groupEnd = dataLength - remainder;
int buffer = 0; byte[] decoded = new byte[(groupEnd / 4) * 3 + (remainder == 0 ? 0 : remainder - 1)];
int bits = 0;
int outputIndex = 0; int outputIndex = 0;
for (int i = 0; i < dataLength; i++) { // Each complete group consumes exactly four characters and writes exactly three bytes.
int value = alphabet.indexOf(input.charAt(i)); for (int i = 0; i < groupEnd; i += 4) {
if (value < 0) { int a = alphabet[input[i] & 0xff];
int b = alphabet[input[i + 1] & 0xff];
int c = alphabet[input[i + 2] & 0xff];
int d = alphabet[input[i + 3] & 0xff];
if ((a | b | c | d) < 0) {
throw new IllegalArgumentException("Invalid Base64 character"); throw new IllegalArgumentException("Invalid Base64 character");
} }
buffer = (buffer << 6) | value; int bits = (a << 18) | (b << 12) | (c << 6) | d;
bits += 6; decoded[outputIndex++] = (byte) (bits >>> 16);
if (bits >= 8) { decoded[outputIndex++] = (byte) (bits >>> 8);
bits -= 8; decoded[outputIndex++] = (byte) bits;
decoded[outputIndex++] = (byte) (buffer >>> bits); }
// The two possible tails consume two or three characters and write one or two bytes.
if (remainder != 0) {
int a = alphabet[input[groupEnd] & 0xff];
int b = alphabet[input[groupEnd + 1] & 0xff];
int c = remainder == 3 ? alphabet[input[groupEnd + 2] & 0xff] : 0;
if ((a | b | c) < 0) {
throw new IllegalArgumentException("Invalid Base64 character");
}
decoded[outputIndex] = (byte) ((a << 2) | (b >>> 4));
if (remainder == 3) {
decoded[outputIndex + 1] = (byte) ((b << 4) | (c >>> 2));
} }
} }
return decoded; return decoded;
} }
private static byte[] alphabet(String characters) {
// Index with an unsigned byte. Every non-alphabet value, including padding, maps to -1.
byte[] table = new byte[256];
Arrays.fill(table, (byte) -1);
for (int i = 0; i < characters.length(); i++) {
table[characters.charAt(i)] = (byte) i;
}
return table;
}
} }
@@ -17,12 +17,31 @@ public class Base64DecoderTest {
public void matchesJdkForStandardAndUrlSafeEncodings() { public void matchesJdkForStandardAndUrlSafeEncodings() {
Random random = new Random(114938); Random random = new Random(114938);
for (int length = 0; length <= 512; length++) { for (int length = 0; length <= 512; length++) {
byte[] value = new byte[length]; assertRoundTrip(random, length);
random.nextBytes(value); }
assertArrayEquals(value, Base64Decoder.decode(Base64.getEncoder().encodeToString(value))); }
assertArrayEquals(value, Base64Decoder.decode(Base64.getEncoder().withoutPadding().encodeToString(value)));
assertArrayEquals(value, Base64Decoder.decodeUrl(Base64.getUrlEncoder().encodeToString(value))); @Test
assertArrayEquals(value, Base64Decoder.decodeUrl(Base64.getUrlEncoder().withoutPadding().encodeToString(value))); public void decodesCompleteGroupsAndEveryTailAcrossLargeInputs() {
Random random = new Random(20261120);
for (int boundary : new int[]{1024, 8192, 65536}) {
for (int offset = -2; offset <= 2; offset++) {
assertRoundTrip(random, boundary + offset);
}
}
}
@Test
public void matchesJdkForInvalidCharactersAtGroupAndTailBoundaries() {
for (int length : new int[]{4, 6, 7, 8}) {
String valid = "A".repeat(length);
for (int i = 0; i < length; i++) {
for (String invalid : new String[]{"!", "=", "\u0141", "\ud83d\ude00"}) {
String value = valid.substring(0, i) + invalid + valid.substring(i + 1);
assertCompatible(value, Base64.getDecoder(), Base64Decoder::decode);
assertCompatible(value, Base64.getUrlDecoder(), Base64Decoder::decodeUrl);
}
}
} }
} }
@@ -47,6 +66,15 @@ public class Base64DecoderTest {
assertEquals("f", CommonUtils.urlBase64Decode("Zg=")); assertEquals("f", CommonUtils.urlBase64Decode("Zg="));
} }
private static void assertRoundTrip(Random random, int length) {
byte[] value = new byte[length];
random.nextBytes(value);
assertArrayEquals(value, Base64Decoder.decode(Base64.getEncoder().encodeToString(value)));
assertArrayEquals(value, Base64Decoder.decode(Base64.getEncoder().withoutPadding().encodeToString(value)));
assertArrayEquals(value, Base64Decoder.decodeUrl(Base64.getUrlEncoder().encodeToString(value)));
assertArrayEquals(value, Base64Decoder.decodeUrl(Base64.getUrlEncoder().withoutPadding().encodeToString(value)));
}
private static void assertCompatible(String value, Base64.Decoder jdk, Function<String, byte[]> replacement) { private static void assertCompatible(String value, Base64.Decoder jdk, Function<String, byte[]> replacement) {
byte[] expected; byte[] expected;
try { try {