diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index ab85458..0c91e69 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -52,6 +52,24 @@ jobs: - name: Maven 编译打包 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: Base64 SIMD 兼容性回归测试 + if: github.event_name == 'pull_request' + run: >- + mvn -B test -DskipTests=false + -Dtest=Base64DecoderTest,HttpProxyBase64Test,Base64CompatibilityTest + -Dsurefire.failIfNoSpecifiedTests=false + "-DargLine=--add-modules=jdk.incubator.vector -XX:-UseBASE64Intrinsics -Dnfd.test.requireVector=true" + --file pom.xml + - name: 更新依赖图谱 uses: advanced-security/maven-dependency-submission-action@v3 if: github.event_name != 'pull_request' diff --git a/Dockerfile b/Dockerfile index be3c89b..19f749b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,5 @@ -FROM eclipse-temurin:17-jre +ARG JAVA_RUNTIME_IMAGE=eclipse-temurin:17-jre +FROM ${JAVA_RUNTIME_IMAGE} WORKDIR /app diff --git a/bin/run.sh b/bin/run.sh old mode 100644 new mode 100755 index 04c111c..377e73c --- a/bin/run.sh +++ b/bin/run.sh @@ -1,5 +1,9 @@ #!/bin/bash # set -x LAUNCH_JAR="netdisk-fast-download.jar" -exec java -Xmx${JVM_XMX:-512M} ${JVM_OPTS} -jar "$LAUNCH_JAR" "$@" +VECTOR_MODULE_OPT= +if java --list-modules 2>/dev/null | grep -q '^jdk.incubator.vector@'; then + VECTOR_MODULE_OPT=--add-modules=jdk.incubator.vector +fi +exec java ${VECTOR_MODULE_OPT} -Xmx${JVM_XMX:-512M} ${JVM_OPTS} -jar "$LAUNCH_JAR" "$@" diff --git a/core/src/main/java/cn/qaiu/vx/core/verticle/HttpProxyVerticle.java b/core/src/main/java/cn/qaiu/vx/core/verticle/HttpProxyVerticle.java index 3ddff9a..930c433 100644 --- a/core/src/main/java/cn/qaiu/vx/core/verticle/HttpProxyVerticle.java +++ b/core/src/main/java/cn/qaiu/vx/core/verticle/HttpProxyVerticle.java @@ -13,7 +13,10 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.ByteArrayInputStream; +import java.io.IOException; import java.net.URI; +import java.nio.charset.StandardCharsets; import java.util.Base64; import static cn.qaiu.vx.core.util.ConfigConstant.GLOBAL_CONFIG; @@ -25,6 +28,20 @@ import static cn.qaiu.vx.core.util.ConfigConstant.LOCAL; public class HttpProxyVerticle extends AbstractVerticle { private static final Logger LOGGER = LoggerFactory.getLogger(HttpProxyVerticle.class); + static byte[] decodeProxyAuthorization(String encoded) { + var source = new ByteArrayInputStream(encoded.getBytes(StandardCharsets.ISO_8859_1)); + // The streaming decoder uses scalar Java code and does not call the bulk intrinsic. + try (var decoder = Base64.getDecoder().wrap(source)) { + byte[] decoded = decoder.readAllBytes(); + if (source.available() != 0) { + throw new IllegalArgumentException("Unexpected data after Base64 padding"); + } + return decoded; + } catch (IOException e) { + throw new IllegalArgumentException("Invalid Base64 proxy credentials", e); + } + } + private HttpClient httpClient; private NetClient netClient; private HttpServer httpServer; @@ -164,7 +181,7 @@ public class HttpProxyVerticle extends AbstractVerticle { } String[] split; try { - split = new String(Base64.getDecoder().decode(s.replace("Basic ", ""))).split(":"); + split = new String(decodeProxyAuthorization(s.replace("Basic ", ""))).split(":"); } catch (IllegalArgumentException e) { LOGGER.warn("Proxy-Authorization header is not valid Base64"); failClientResponse(clientRequest.response(), 403, null); diff --git a/core/src/test/java/cn/qaiu/vx/core/verticle/HttpProxyBase64Test.java b/core/src/test/java/cn/qaiu/vx/core/verticle/HttpProxyBase64Test.java new file mode 100644 index 0000000..db72330 --- /dev/null +++ b/core/src/test/java/cn/qaiu/vx/core/verticle/HttpProxyBase64Test.java @@ -0,0 +1,30 @@ +package cn.qaiu.vx.core.verticle; + +import org.junit.Test; + +import java.util.Base64; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.fail; + +public class HttpProxyBase64Test { + @Test + public void matchesJdkBasicDecoder() { + for (String value : new String[]{"", "Zg", "Zg==", "Zm8=", "dXNlcjpwYXNz", "+/8=", "ABCD", + "AB==", "Z", "Zg=", "Zm8==", "Zg==suffix", "Zg==\n", "-_8=", "AA\u2603", "===="}) { + byte[] expected; + try { + expected = Base64.getDecoder().decode(value); + } catch (IllegalArgumentException expectedFailure) { + try { + HttpProxyVerticle.decodeProxyAuthorization(value); + } catch (IllegalArgumentException actualFailure) { + continue; + } + fail("Accepted invalid proxy credentials: " + value); + return; + } + assertArrayEquals(expected, HttpProxyVerticle.decodeProxyAuthorization(value)); + } + } +} diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 7742770..3759692 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -10,4 +10,9 @@ DEFAULT_JVM_OPTS="-Xmx${JVM_XMX:-512M} -Xss${JVM_XSS:-512k} -XX:MaxDirectMemoryS if [ -n "${JVM_MAX_METASPACE:-}" ]; then DEFAULT_JVM_OPTS="$DEFAULT_JVM_OPTS -XX:MaxMetaspaceSize=$JVM_MAX_METASPACE" fi -exec java ${DEFAULT_JVM_OPTS} ${JVM_OPTS} -Duser.timezone=${TZ:-Asia/Shanghai} -jar /app/netdisk-fast-download.jar +# Keep this after JVM_OPTS to disable the intrinsic even with an older base image. +VECTOR_MODULE_OPT= +if java --list-modules 2>/dev/null | grep -q '^jdk.incubator.vector@'; then + VECTOR_MODULE_OPT=--add-modules=jdk.incubator.vector +fi +exec java ${VECTOR_MODULE_OPT} ${DEFAULT_JVM_OPTS} ${JVM_OPTS} -XX:-UseBASE64Intrinsics -Duser.timezone=${TZ:-Asia/Shanghai} -jar /app/netdisk-fast-download.jar diff --git a/parser/pom.xml b/parser/pom.xml index 50dee03..c5909f0 100644 --- a/parser/pom.xml +++ b/parser/pom.xml @@ -165,6 +165,10 @@ 3.13.0 ${maven.compiler.source} + + --add-modules + jdk.incubator.vector + ${project.build.sourceEncoding} @@ -200,7 +204,11 @@ false - -Xdoclint:none + + -Xdoclint:none + --add-modules + jdk.incubator.vector + true diff --git a/parser/src/main/java/cn/qaiu/parser/clientlink/impl/ThunderLinkGenerator.java b/parser/src/main/java/cn/qaiu/parser/clientlink/impl/ThunderLinkGenerator.java index db3e509..100614a 100644 --- a/parser/src/main/java/cn/qaiu/parser/clientlink/impl/ThunderLinkGenerator.java +++ b/parser/src/main/java/cn/qaiu/parser/clientlink/impl/ThunderLinkGenerator.java @@ -1,11 +1,11 @@ package cn.qaiu.parser.clientlink.impl; +import cn.qaiu.util.Base64Encoder; import cn.qaiu.parser.clientlink.ClientLinkGenerator; import cn.qaiu.parser.clientlink.ClientLinkType; import cn.qaiu.parser.clientlink.DownloadLinkMeta; import java.nio.charset.StandardCharsets; -import java.util.Base64; /** * 迅雷协议链接生成器 @@ -27,7 +27,7 @@ public class ThunderLinkGenerator implements ClientLinkGenerator { String thunderUrl = "AA" + originalUrl + "ZZ"; // Base64编码 - String encodedUrl = Base64.getEncoder().encodeToString( + String encodedUrl = Base64Encoder.encode( thunderUrl.getBytes(StandardCharsets.UTF_8) ); diff --git a/parser/src/main/java/cn/qaiu/parser/impl/GenShortUrl.java b/parser/src/main/java/cn/qaiu/parser/impl/GenShortUrl.java index c814f10..5b20a40 100644 --- a/parser/src/main/java/cn/qaiu/parser/impl/GenShortUrl.java +++ b/parser/src/main/java/cn/qaiu/parser/impl/GenShortUrl.java @@ -1,5 +1,6 @@ package cn.qaiu.parser.impl; +import cn.qaiu.util.Base64Encoder; import cn.qaiu.entity.ShareLinkInfo; import cn.qaiu.parser.PanBase; import io.netty.handler.codec.http.cookie.Cookie; @@ -14,7 +15,6 @@ import org.slf4j.LoggerFactory; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import java.util.Base64; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -48,7 +48,7 @@ public class GenShortUrl extends PanBase { public Future parse() { String longUrl = shareLinkInfo.getShareUrl(); - String url = WRAPPER_URL + Base64.getEncoder().encodeToString(longUrl.getBytes()); + String url = WRAPPER_URL + Base64Encoder.encode(longUrl.getBytes()); String payload = "mid=" + MID + "&content=" + URLEncoder.encode(url, StandardCharsets.UTF_8); clientSession.cookieStore().put(cookie); diff --git a/parser/src/main/java/cn/qaiu/parser/impl/LeTool.java b/parser/src/main/java/cn/qaiu/parser/impl/LeTool.java index e999b9a..03406e2 100644 --- a/parser/src/main/java/cn/qaiu/parser/impl/LeTool.java +++ b/parser/src/main/java/cn/qaiu/parser/impl/LeTool.java @@ -1,5 +1,6 @@ package cn.qaiu.parser.impl; +import cn.qaiu.util.Base64Encoder; import cn.qaiu.entity.FileInfo; import cn.qaiu.entity.ShareLinkInfo; import cn.qaiu.parser.PanBase; @@ -13,7 +14,6 @@ import io.vertx.core.json.JsonObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; -import java.util.Base64; import java.util.List; import java.util.Random; import java.util.UUID; @@ -232,7 +232,7 @@ public class LeTool extends PanBase { "shareId", shareId, "fileId", fileId ); - String paramBase64 = Base64.getEncoder().encodeToString(paramJson.encode().getBytes()); + String paramBase64 = Base64Encoder.encode(paramJson.encode().getBytes()); // 设置解析URL和预览URL fileInfo.setParserUrl(String.format("%s/v2/redirectUrl/%s/%s", diff --git a/parser/src/main/java/cn/qaiu/parser/impl/Ye2Tool.java b/parser/src/main/java/cn/qaiu/parser/impl/Ye2Tool.java index 3f99697..329e737 100644 --- a/parser/src/main/java/cn/qaiu/parser/impl/Ye2Tool.java +++ b/parser/src/main/java/cn/qaiu/parser/impl/Ye2Tool.java @@ -6,6 +6,7 @@ import cn.qaiu.parser.PanBase; import cn.qaiu.parser.PasswordLoginRisk; import cn.qaiu.parser.TokenCache; import cn.qaiu.util.CommonUtils; +import cn.qaiu.util.Base64Decoder; import cn.qaiu.util.FileSizeConverter; import cn.qaiu.util.YeShareHostUtil; import io.vertx.core.Future; @@ -23,7 +24,6 @@ import java.net.MalformedURLException; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; -import java.util.Base64; import java.util.List; import java.util.Map; import java.util.Random; @@ -514,7 +514,7 @@ public class Ye2Tool extends PanBase { return; } - byte[] decodeByte = Base64.getDecoder().decode(params); + byte[] decodeByte = Base64Decoder.decode(params); String downUrl2 = new String(decodeByte); clientNoRedirects.getAbs(downUrl2).putHeaders(header).send().onSuccess(res3 -> { diff --git a/parser/src/main/java/cn/qaiu/parser/impl/YeTool.java b/parser/src/main/java/cn/qaiu/parser/impl/YeTool.java index 4757d4e..0f430df 100644 --- a/parser/src/main/java/cn/qaiu/parser/impl/YeTool.java +++ b/parser/src/main/java/cn/qaiu/parser/impl/YeTool.java @@ -1,9 +1,11 @@ package cn.qaiu.parser.impl; +import cn.qaiu.util.Base64Encoder; import cn.qaiu.entity.FileInfo; import cn.qaiu.entity.ShareLinkInfo; import cn.qaiu.parser.PanBase; import cn.qaiu.util.CommonUtils; +import cn.qaiu.util.Base64Decoder; import cn.qaiu.util.FileSizeConverter; import cn.qaiu.util.JsExecUtils; import io.vertx.core.Future; @@ -21,7 +23,6 @@ import java.net.MalformedURLException; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; -import java.util.Base64; import java.util.List; import java.util.Map; import java.util.regex.Matcher; @@ -166,7 +167,7 @@ public class YeTool extends PanBase { try { Map urlParams = CommonUtils.getURLParams(downURL); String params = urlParams.get("params"); - byte[] decodeByte = Base64.getDecoder().decode(params); + byte[] decodeByte = Base64Decoder.decode(params); String downUrl2 = new String(decodeByte); // 获取直链 @@ -261,7 +262,7 @@ public class YeTool extends PanBase { .put("Size", item.getLong("Size")) .put("Etag", item.getString("Etag")); - byte[] encode = Base64.getEncoder().encode(postData.encode().getBytes()); + byte[] encode = Base64Encoder.encodeBytes(postData.encode().getBytes()); String param = new String(encode); if (item.getInteger("Type") == 0) { // 文件 diff --git a/parser/src/main/java/cn/qaiu/util/AESUtils.java b/parser/src/main/java/cn/qaiu/util/AESUtils.java index a3a42b0..8c6c8aa 100644 --- a/parser/src/main/java/cn/qaiu/util/AESUtils.java +++ b/parser/src/main/java/cn/qaiu/util/AESUtils.java @@ -11,7 +11,6 @@ import java.nio.charset.StandardCharsets; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; -import java.util.Base64; import java.util.Date; import java.util.HexFormat; import java.util.regex.Matcher; @@ -131,13 +130,13 @@ public class AESUtils { public static String encryptBase64ByAES(String source, String keyString) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] encrypted = encryptByAES(source, keyString); - return Base64.getEncoder().encodeToString(encrypted); + return Base64Encoder.encode(encrypted); } public static String encryptBase64ByAES(String source, Key key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] encrypted = encryptByAES(source, key); - return Base64.getEncoder().encodeToString(encrypted); + return Base64Encoder.encode(encrypted); } /** @@ -219,12 +218,12 @@ public class AESUtils { */ public static String decryptByBase64AES(String encrypted, String keyString) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException { - return decryptByAES(Base64.getDecoder().decode(encrypted), keyString); + return decryptByAES(Base64Decoder.decode(encrypted), keyString); } public static String decryptByBase64AES(String encrypted, Key key) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException { - return decryptByAES(Base64.getDecoder().decode(encrypted), key); + return decryptByAES(Base64Decoder.decode(encrypted), key); } // ================================飞机盘Id解密========================================== // diff --git a/parser/src/main/java/cn/qaiu/util/Base64Decoder.java b/parser/src/main/java/cn/qaiu/util/Base64Decoder.java new file mode 100644 index 0000000..312e5d1 --- /dev/null +++ b/parser/src/main/java/cn/qaiu/util/Base64Decoder.java @@ -0,0 +1,87 @@ +package cn.qaiu.util; + +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 { + private static final byte[] BASIC = alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"); + private static final byte[] URL_SAFE = alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"); + + private Base64Decoder() { + } + + public static byte[] decode(String input) { + return decode(input.getBytes(StandardCharsets.ISO_8859_1), BASIC); + } + + public static byte[] decodeUrl(String input) { + return decode(input.getBytes(StandardCharsets.ISO_8859_1), URL_SAFE); + } + + private static byte[] decode(byte[] input, byte[] alphabet) { + int length = input.length; + int dataLength = length; + if (dataLength > 0 && input[dataLength - 1] == '=') { + dataLength--; + if (dataLength > 0 && input[dataLength - 1] == '=') { + dataLength--; + } + } + + int remainder = dataLength % 4; + int padding = length - dataLength; + if (remainder == 1 || (padding != 0 && remainder + padding != 4)) { + throw new IllegalArgumentException("Invalid Base64 padding or length"); + } + + int groupEnd = dataLength - remainder; + byte[] decoded = new byte[(groupEnd / 4) * 3 + (remainder == 0 ? 0 : remainder - 1)]; + int start = Base64Encoder.useVectors(groupEnd) + ? VectorBase64.decode(input, groupEnd, decoded, alphabet == URL_SAFE) : 0; + int outputIndex = start / 4 * 3; + // Each complete group consumes exactly four characters and writes exactly three bytes. + for (int i = start; i < groupEnd; i += 4) { + 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"); + } + int bits = (a << 18) | (b << 12) | (c << 6) | d; + decoded[outputIndex++] = (byte) (bits >>> 16); + decoded[outputIndex++] = (byte) (bits >>> 8); + decoded[outputIndex++] = (byte) 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; + } + + 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; + } +} diff --git a/parser/src/main/java/cn/qaiu/util/Base64Encoder.java b/parser/src/main/java/cn/qaiu/util/Base64Encoder.java new file mode 100644 index 0000000..98abdb0 --- /dev/null +++ b/parser/src/main/java/cn/qaiu/util/Base64Encoder.java @@ -0,0 +1,75 @@ +package cn.qaiu.util; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +public final class Base64Encoder { + private static final boolean VECTORS = vectorsAvailable(); + static final String BASIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + static final String URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + + private Base64Encoder() {} + + private static boolean vectorsAvailable() { + if (java.nio.ByteOrder.nativeOrder() != java.nio.ByteOrder.LITTLE_ENDIAN + || ModuleLayer.boot().findModule("jdk.incubator.vector").isEmpty()) { + return false; + } + try { + return VectorBase64.available(); + } catch (LinkageError unavailableOnThisJdk) { + return false; + } + } + + static boolean useVectors(int length) { + return VECTORS && length >= 1024; + } + + public static String encode(byte[] data) { + return useVectors(data.length) ? new String(vectorEncode(data, false), StandardCharsets.ISO_8859_1) + : Base64.getEncoder().encodeToString(data); + } + + public static byte[] encodeBytes(byte[] data) { + return useVectors(data.length) ? vectorEncode(data, false) : Base64.getEncoder().encode(data); + } + + public static String encodeUrlWithoutPadding(byte[] data) { + return useVectors(data.length) ? new String(vectorEncode(data, true), StandardCharsets.ISO_8859_1) + : Base64.getUrlEncoder().withoutPadding().encodeToString(data); + } + + private static byte[] vectorEncode(byte[] input, boolean url) { + int remainder = input.length % 3; + int tailLength = remainder + 1; + if (remainder == 0) { + tailLength = 0; + } else if (!url) { + tailLength = 4; + } + long length = (long) (input.length / 3) * 4 + tailLength; + if (length > Integer.MAX_VALUE) { + throw new OutOfMemoryError("Base64 output exceeds maximum array length"); + } + byte[] output = new byte[(int) length]; + int src = VectorBase64.encode(input, output, url); + int dst = src / 3 * 4; + String alphabet = url ? URL : BASIC; + while (src < input.length) { + int bytes = Math.min(3, input.length - src); + int bits = (input[src++] & 255) << 16; + if (bytes >= 2) { + bits |= (input[src++] & 255) << 8; + } + if (bytes == 3) { + bits |= input[src++] & 255; + } + for (int shift = 18; shift >= 18 - bytes * 6; shift -= 6) { + output[dst++] = (byte) alphabet.charAt((bits >>> shift) & 63); + } + } + java.util.Arrays.fill(output, dst, output.length, (byte) '='); + return output; + } +} diff --git a/parser/src/main/java/cn/qaiu/util/CommonUtils.java b/parser/src/main/java/cn/qaiu/util/CommonUtils.java index afc4ec9..bce042d 100644 --- a/parser/src/main/java/cn/qaiu/util/CommonUtils.java +++ b/parser/src/main/java/cn/qaiu/util/CommonUtils.java @@ -100,12 +100,12 @@ public class CommonUtils { Exception last = null; for (String candidate : new String[]{s, padBase64(s)}) { try { - return new String(java.util.Base64.getUrlDecoder().decode(candidate), StandardCharsets.UTF_8); + return new String(Base64Decoder.decodeUrl(candidate), StandardCharsets.UTF_8); } catch (Exception e) { last = e; } try { - return new String(java.util.Base64.getDecoder().decode(candidate), StandardCharsets.UTF_8); + return new String(Base64Decoder.decode(candidate), StandardCharsets.UTF_8); } catch (Exception e) { last = e; } @@ -118,9 +118,7 @@ public class CommonUtils { *

不再做 URLEncoder,避免前端/代理再 encode 时变成 %253D。

*/ public static String urlBase64Encode(String str) { - return java.util.Base64.getUrlEncoder() - .withoutPadding() - .encodeToString(str.getBytes(StandardCharsets.UTF_8)); + return Base64Encoder.encodeUrlWithoutPadding(str.getBytes(StandardCharsets.UTF_8)); } private static String padBase64(String s) { diff --git a/parser/src/main/java/cn/qaiu/util/VectorBase64.java b/parser/src/main/java/cn/qaiu/util/VectorBase64.java new file mode 100644 index 0000000..0ca1034 --- /dev/null +++ b/parser/src/main/java/cn/qaiu/util/VectorBase64.java @@ -0,0 +1,125 @@ +package cn.qaiu.util; + +import jdk.incubator.vector.ByteVector; +import jdk.incubator.vector.IntVector; +import jdk.incubator.vector.VectorMask; +import jdk.incubator.vector.VectorShuffle; +import jdk.incubator.vector.VectorSpecies; + +import static jdk.incubator.vector.VectorOperators.*; + +final class VectorBase64 { + private static final VectorSpecies SPECIES = ByteVector.SPECIES_PREFERRED; + private static final int WIDTH = SPECIES.length(); + private static final int PACKED = WIDTH / 4 * 3; + private static final VectorMask PACKED_MASK = SPECIES.indexInRange(0, PACKED); + // Each four-byte lane holds one quartet. Pack or expand its three binary bytes. + private static final VectorShuffle PACK = VectorShuffle.fromOp(SPECIES, + i -> i < PACKED ? i / 3 * 4 + i % 3 : 0); + private static final VectorShuffle EXPAND = VectorShuffle.fromOp(SPECIES, + i -> i / 4 * 3 + Math.min(i % 4, 2)); + + // Each low-nibble entry is a bit set of allowed high nibbles. + private static final class Alphabet { + final ByteVector lowMasks; + final ByteVector highMasks; + final ByteVector offsets; + final byte last; + final ByteVector encodeTable; + + Alphabet(String letters) { + byte[] low = new byte[Math.max(WIDTH, 16)]; + byte[] high = new byte[low.length]; + byte[] offset = new byte[low.length]; + byte[] chars = new byte[WIDTH]; + if (WIDTH >= 64) { + for (int i = 0; i < 64; i++) { + chars[i] = (byte) letters.charAt(i); + } + } + encodeTable = ByteVector.fromArray(SPECIES, chars, 0); + last = (byte) letters.charAt(63); + for (int i = 0; i < letters.length(); i++) { + int ch = letters.charAt(i); + int bucket = ch >>> 4; + byte bit = (byte) (1 << bucket); + high[bucket] = bit; + low[ch & 15] |= bit; + if (ch != last) { + offset[bucket] = (byte) (i - ch); + } + } + lowMasks = ByteVector.fromArray(SPECIES, low, 0); + highMasks = ByteVector.fromArray(SPECIES, high, 0); + offsets = ByteVector.fromArray(SPECIES, offset, 0); + } + } + + private static final Alphabet BASIC = new Alphabet(Base64Encoder.BASIC); + private static final Alphabet URL = new Alphabet(Base64Encoder.URL); + + private VectorBase64() {} + + static boolean available() { + if (WIDTH < 16) { + return false; + } + // Incubator APIs can change between JDK releases. Link both kernels before enabling them. + byte[] plain = new byte[PACKED]; + byte[] encoded = new byte[WIDTH]; + byte[] decoded = new byte[PACKED]; + plain[0] = (byte) 0xfb; + encode(plain, encoded, true); + decode(encoded, WIDTH, decoded, true); + return encoded[0] == '-' && java.util.Arrays.equals(plain, decoded); + } + + static int decode(byte[] input, int groupEnd, byte[] output, boolean url) { + Alphabet alphabet = url ? URL : BASIC; + int limit = SPECIES.loopBound(groupEnd); + int dst = 0; + for (int src = 0; src < limit; src += WIDTH) { + ByteVector ascii = ByteVector.fromArray(SPECIES, input, src); + ByteVector high = ascii.lanewise(LSHR, 4); + ByteVector low = ascii.and((byte) 15); + // The low-nibble table records which high nibbles form legal characters. + if (high.selectFrom(alphabet.highMasks).and(low.selectFrom(alphabet.lowMasks)).eq((byte) 0).anyTrue()) { + throw new IllegalArgumentException("Invalid Base64 character"); + } + ByteVector values = ascii.add(high.selectFrom(alphabet.offsets)).blend((byte) 63, ascii.eq(alphabet.last)); + // [a,b,c,d] -> [(a<<2)|(b>>4), (b<<4)|(c>>2), (c<<6)|d, unused]. + IntVector w = values.reinterpretAsInts(); + IntVector bytes = w.lanewise(LSHL, 2).and(0xfc).or(w.lanewise(LSHR, 12).and(3)) + .or(w.lanewise(LSHL, 4).and(0xf000)).or(w.lanewise(LSHR, 10).and(0x0f00)) + .or(w.lanewise(LSHL, 6).and(0xc00000)).or(w.lanewise(LSHR, 8).and(0x3f0000)); + bytes.reinterpretAsBytes().rearrange(PACK).intoArray(output, dst, PACKED_MASK); + dst += PACKED; + } + return limit; + } + + static int encode(byte[] input, byte[] output, boolean url) { + int limit = input.length / PACKED * PACKED; + int dst = 0; + for (int src = 0; src < limit; src += PACKED) { + IntVector w = ByteVector.fromArray(SPECIES, input, src, PACKED_MASK) + .rearrange(EXPAND).reinterpretAsInts(); + // Undo the quartet packing, extracting four six-bit indices per lane. + IntVector indices = w.lanewise(LSHR, 2).and(63) + .or(w.lanewise(LSHL, 12).and(0x3000)).or(w.lanewise(LSHR, 4).and(0x0f00)) + .or(w.lanewise(LSHL, 10).and(0x3c0000)).or(w.lanewise(LSHR, 6).and(0x030000)) + .or(w.lanewise(LSHL, 8).and(0x3f000000)); + ByteVector v = indices.reinterpretAsBytes(); + if (WIDTH >= 64) { + v.selectFrom((url ? URL : BASIC).encodeTable).intoArray(output, dst); + } else { + v.add((byte) 'A').blend(v.add((byte) ('a' - 26)), v.compare(GE, (byte) 26)) + .blend(v.add((byte) ('0' - 52)), v.compare(GE, (byte) 52)) + .blend((byte) (url ? '-' : '+'), v.eq((byte) 62)) + .blend((byte) (url ? '_' : '/'), v.eq((byte) 63)).intoArray(output, dst); + } + dst += WIDTH; + } + return limit; + } +} diff --git a/parser/src/test/java/cn/qaiu/util/Base64DecoderTest.java b/parser/src/test/java/cn/qaiu/util/Base64DecoderTest.java new file mode 100644 index 0000000..6952e1c --- /dev/null +++ b/parser/src/test/java/cn/qaiu/util/Base64DecoderTest.java @@ -0,0 +1,127 @@ +package cn.qaiu.util; + +import org.junit.Test; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Random; +import java.util.function.Function; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +public class Base64DecoderTest { + @Test + public void matchesJdkForStandardAndUrlSafeEncodings() { + Random random = new Random(114938); + for (int length = 0; length <= 512; length++) { + assertRoundTrip(random, length); + } + } + + @Test + 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); + } + } + } + } + + @Test + public void matchesJdkForPaddingAlphabetAndInvalidCharacters() { + for (String value : new String[]{"", "A", "AA", "AB==", "ABC=", "ABCD", "AA=", "AAA==", + "AA==AA", "AA==\n", " AA", "A A", "AA\u00e9", "AA\u2603", "+/8=", "-_8=", "+_8=", "===="}) { + assertCompatible(value, Base64.getDecoder(), Base64Decoder::decode); + assertCompatible(value, Base64.getUrlDecoder(), Base64Decoder::decodeUrl); + } + } + + @Test + public void preservesLegacyDownloadLinkFormats() { + String value = "网盘下载😀"; + String standard = Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8)); + String escaped = URLEncoder.encode(standard, StandardCharsets.UTF_8); + assertEquals(value, CommonUtils.urlBase64Decode(CommonUtils.urlBase64Encode(value))); + assertEquals(value, CommonUtils.urlBase64Decode(standard)); + assertEquals(value, CommonUtils.urlBase64Decode(escaped)); + assertEquals(value, CommonUtils.urlBase64Decode(URLEncoder.encode(escaped, StandardCharsets.UTF_8))); + assertEquals("f", CommonUtils.urlBase64Decode("Zg=")); + } + + @Test + public void matchesJdkAcrossSimdBlocksAndThreshold() { + if (Boolean.getBoolean("nfd.test.requireVector")) { + assertEquals(true, Base64Encoder.useVectors(4096)); + } + Random random = new Random(114938); + for (int boundary : new int[]{768, 1024, 4096}) { + for (int offset = -65; offset <= 65; offset++) { + byte[] plain = new byte[boundary + offset]; + random.nextBytes(plain); + String standard = Base64.getEncoder().encodeToString(plain); + String url = Base64.getUrlEncoder().withoutPadding().encodeToString(plain); + assertEquals(standard, Base64Encoder.encode(plain)); + assertEquals(url, Base64Encoder.encodeUrlWithoutPadding(plain)); + assertArrayEquals(Base64.getEncoder().encode(plain), Base64Encoder.encodeBytes(plain)); + assertArrayEquals(plain, Base64Decoder.decode(standard)); + assertArrayEquals(plain, Base64Decoder.decodeUrl(url)); + } + } + } + + @Test + public void validatesBothAlphabetsInsideVectorBlocks() { + char[] input = "A".repeat(2048).toCharArray(); + for (int ch = 0; ch < 256; ch++) { + int position = 128 + ch % 64; + input[position] = (char) ch; + String encoded = new String(input); + assertCompatible(encoded, Base64.getDecoder(), Base64Decoder::decode); + assertCompatible(encoded, Base64.getUrlDecoder(), Base64Decoder::decodeUrl); + input[position] = 'A'; + } + } + + 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 replacement) { + byte[] expected; + try { + expected = jdk.decode(value); + } catch (IllegalArgumentException expectedFailure) { + try { + replacement.apply(value); + } catch (IllegalArgumentException actualFailure) { + return; + } + fail("Accepted invalid Base64 input: " + value); + return; + } + assertArrayEquals(expected, replacement.apply(value)); + } +} diff --git a/pom.xml b/pom.xml index 3c11261..97ab7e6 100644 --- a/pom.xml +++ b/pom.xml @@ -36,6 +36,7 @@ 2.18.9 1.5.34 + true 4.13.2 @@ -97,7 +98,7 @@ maven-surefire-plugin 2.22.2 - true + ${skipTests} diff --git a/web-service/src/main/java/cn/qaiu/lz/common/util/AuthParamCodec.java b/web-service/src/main/java/cn/qaiu/lz/common/util/AuthParamCodec.java index 0a9c1f2..599fb28 100644 --- a/web-service/src/main/java/cn/qaiu/lz/common/util/AuthParamCodec.java +++ b/web-service/src/main/java/cn/qaiu/lz/common/util/AuthParamCodec.java @@ -2,6 +2,7 @@ package cn.qaiu.lz.common.util; import cn.qaiu.lz.web.model.AuthParam; import cn.qaiu.util.AESUtils; +import cn.qaiu.util.Base64Decoder; import cn.qaiu.vx.core.util.SharedDataUtil; import io.vertx.core.json.JsonObject; import lombok.extern.slf4j.Slf4j; @@ -9,7 +10,6 @@ import org.apache.commons.lang3.StringUtils; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; -import java.util.Base64; /** * 认证参数编解码工具类 @@ -88,7 +88,7 @@ public class AuthParamCodec { log.debug("认证参数规范化结果: {}", normalized); // Step 2: Base64解码 - byte[] base64Decoded = Base64.getDecoder().decode(normalized); + byte[] base64Decoded = Base64Decoder.decode(normalized); log.debug("Base64解码成功,长度: {}", base64Decoded.length); // Step 3: AES解密 diff --git a/web-service/src/main/java/cn/qaiu/lz/common/util/JwtUtil.java b/web-service/src/main/java/cn/qaiu/lz/common/util/JwtUtil.java index 0da695f..5cb143c 100644 --- a/web-service/src/main/java/cn/qaiu/lz/common/util/JwtUtil.java +++ b/web-service/src/main/java/cn/qaiu/lz/common/util/JwtUtil.java @@ -1,5 +1,7 @@ package cn.qaiu.lz.common.util; +import cn.qaiu.util.Base64Encoder; +import cn.qaiu.util.Base64Decoder; import cn.qaiu.lz.web.model.SysUser; import io.vertx.core.json.JsonObject; @@ -12,7 +14,6 @@ import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; -import java.util.Base64; import java.util.Date; /** @@ -48,8 +49,8 @@ public class JwtUtil { .put("iss", "netdisk-fast-download"); // Base64 encode header and payload - String encodedHeader = Base64.getUrlEncoder().withoutPadding().encodeToString(header.encode().getBytes(StandardCharsets.UTF_8)); - String encodedPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(payload.encode().getBytes(StandardCharsets.UTF_8)); + String encodedHeader = Base64Encoder.encodeUrlWithoutPadding(header.encode().getBytes(StandardCharsets.UTF_8)); + String encodedPayload = Base64Encoder.encodeUrlWithoutPadding(payload.encode().getBytes(StandardCharsets.UTF_8)); // Create signature String signature = hmacSha256(encodedHeader + "." + encodedPayload, SECRET_KEY); @@ -71,7 +72,7 @@ public class JwtUtil { SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGORITHM); sha256Hmac.init(secretKey); byte[] signedBytes = sha256Hmac.doFinal(data.getBytes(StandardCharsets.UTF_8)); - return Base64.getUrlEncoder().withoutPadding().encodeToString(signedBytes); + return Base64Encoder.encodeUrlWithoutPadding(signedBytes); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException("Error creating HMAC SHA256 signature", e); } @@ -102,7 +103,7 @@ public class JwtUtil { } // 验证过期时间 - String payload = new String(Base64.getUrlDecoder().decode(encodedPayload), StandardCharsets.UTF_8); + String payload = new String(Base64Decoder.decodeUrl(encodedPayload), StandardCharsets.UTF_8); JsonObject payloadJson = new JsonObject(payload); long expTime = payloadJson.getLong("exp", 0L); @@ -125,7 +126,7 @@ public class JwtUtil { } // Base64解码 - String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); + String payload = new String(Base64Decoder.decodeUrl(parts[1]), StandardCharsets.UTF_8); JsonObject jsonObject = new JsonObject(payload); return jsonObject.getString("id"); } @@ -143,7 +144,7 @@ public class JwtUtil { } // Base64解码 - String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); + String payload = new String(Base64Decoder.decodeUrl(parts[1]), StandardCharsets.UTF_8); JsonObject jsonObject = new JsonObject(payload); return jsonObject.getString("username"); } @@ -161,7 +162,7 @@ public class JwtUtil { } // Base64解码 - String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); + String payload = new String(Base64Decoder.decodeUrl(parts[1]), StandardCharsets.UTF_8); JsonObject jsonObject = new JsonObject(payload); return jsonObject.getString("role"); } diff --git a/web-service/src/main/java/cn/qaiu/lz/common/util/PasswordUtil.java b/web-service/src/main/java/cn/qaiu/lz/common/util/PasswordUtil.java index 62c466f..1c7c6b1 100644 --- a/web-service/src/main/java/cn/qaiu/lz/common/util/PasswordUtil.java +++ b/web-service/src/main/java/cn/qaiu/lz/common/util/PasswordUtil.java @@ -1,5 +1,7 @@ package cn.qaiu.lz.common.util; +import cn.qaiu.util.Base64Encoder; +import cn.qaiu.util.Base64Decoder; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -39,8 +41,8 @@ public class PasswordUtil { byte[] hashedPassword = md.digest(plainPassword.getBytes(StandardCharsets.UTF_8)); // 将盐和哈希值编码为Base64并拼接 - String saltBase64 = Base64.getEncoder().encodeToString(salt); - String hashBase64 = Base64.getEncoder().encodeToString(hashedPassword); + String saltBase64 = Base64Encoder.encode(salt); + String hashBase64 = Base64Encoder.encode(hashedPassword); // 返回格式:salt:hash return saltBase64 + DELIMITER + hashBase64; @@ -72,13 +74,13 @@ public class PasswordUtil { String hashBase64 = parts[1]; // 解码盐 - byte[] salt = Base64.getDecoder().decode(saltBase64); + byte[] salt = Base64Decoder.decode(saltBase64); // 使用相同的盐计算哈希值 MessageDigest md = MessageDigest.getInstance(ALGORITHM); md.update(salt); byte[] calculatedHash = md.digest(plainPassword.getBytes(StandardCharsets.UTF_8)); - String calculatedHashBase64 = Base64.getEncoder().encodeToString(calculatedHash); + String calculatedHashBase64 = Base64Encoder.encode(calculatedHash); // 比较计算出的哈希值和存储的哈希值(使用常量时间比较防止时序攻击) return MessageDigest.isEqual( diff --git a/web-service/src/main/java/cn/qaiu/lz/web/service/impl/DbServiceImpl.java b/web-service/src/main/java/cn/qaiu/lz/web/service/impl/DbServiceImpl.java index fbf88a1..4cd7564 100644 --- a/web-service/src/main/java/cn/qaiu/lz/web/service/impl/DbServiceImpl.java +++ b/web-service/src/main/java/cn/qaiu/lz/web/service/impl/DbServiceImpl.java @@ -1,5 +1,7 @@ package cn.qaiu.lz.web.service.impl; +import cn.qaiu.util.Base64Encoder; +import cn.qaiu.util.Base64Decoder; import cn.qaiu.db.pool.JDBCPoolInit; import cn.qaiu.lz.common.model.UserInfo; import cn.qaiu.lz.web.model.StatisticsInfo; @@ -21,7 +23,6 @@ import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.ArrayList; -import java.util.Base64; import java.util.HashMap; import java.util.List; @@ -457,9 +458,9 @@ public class DbServiceImpl implements DbService { long issuedAt = System.currentTimeMillis(); String payload = accountId + ":" + issuedAt; String signature = hmacSha256(payload); - String token = Base64.getUrlEncoder().withoutPadding().encodeToString(payload.getBytes(StandardCharsets.UTF_8)) + String token = Base64Encoder.encodeUrlWithoutPadding(payload.getBytes(StandardCharsets.UTF_8)) + "." - + Base64.getUrlEncoder().withoutPadding().encodeToString(signature.getBytes(StandardCharsets.UTF_8)); + + Base64Encoder.encodeUrlWithoutPadding(signature.getBytes(StandardCharsets.UTF_8)); return Future.succeededFuture(token); } catch (Exception e) { return Future.failedFuture(e); @@ -526,7 +527,7 @@ public class DbServiceImpl implements DbService { private boolean isLikelyEncrypted(String value) { try { - byte[] decoded = Base64.getDecoder().decode(value); + byte[] decoded = Base64Decoder.decode(value); return decoded.length > 16; } catch (Exception e) { return false; @@ -538,8 +539,8 @@ public class DbServiceImpl implements DbService { throw new IllegalArgumentException("invalid donated account token"); } String[] parts = token.split("\\.", 2); - String payload = new String(Base64.getUrlDecoder().decode(parts[0]), StandardCharsets.UTF_8); - String signature = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8); + String payload = new String(Base64Decoder.decodeUrl(parts[0]), StandardCharsets.UTF_8); + String signature = new String(Base64Decoder.decodeUrl(parts[1]), StandardCharsets.UTF_8); String expected = hmacSha256(payload); if (!expected.equals(signature)) { throw new IllegalArgumentException("donated account token signature invalid"); @@ -562,7 +563,7 @@ public class DbServiceImpl implements DbService { Mac mac = Mac.getInstance(HMAC_ALGORITHM); mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_ALGORITHM)); byte[] digest = mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)); - return Base64.getEncoder().encodeToString(digest); + return Base64Encoder.encode(digest); } private String getDonatedAccountFailureTokenSignKey() { diff --git a/web-service/src/main/java/cn/qaiu/lz/web/util/CryptoUtil.java b/web-service/src/main/java/cn/qaiu/lz/web/util/CryptoUtil.java index b2fc3cc..a705e15 100644 --- a/web-service/src/main/java/cn/qaiu/lz/web/util/CryptoUtil.java +++ b/web-service/src/main/java/cn/qaiu/lz/web/util/CryptoUtil.java @@ -1,5 +1,7 @@ package cn.qaiu.lz.web.util; +import cn.qaiu.util.Base64Encoder; +import cn.qaiu.util.Base64Decoder; import cn.qaiu.vx.core.util.ConfigUtil; import cn.qaiu.vx.core.util.VertxHolder; import io.vertx.core.Future; @@ -13,7 +15,6 @@ import javax.crypto.spec.SecretKeySpec; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; -import java.util.Base64; public class CryptoUtil { @@ -68,7 +69,7 @@ public class CryptoUtil { byteBuffer.put(iv); byteBuffer.put(cipherText); - return Future.succeededFuture(Base64.getEncoder().encodeToString(byteBuffer.array())); + return Future.succeededFuture(Base64Encoder.encode(byteBuffer.array())); } catch (Exception e) { return Future.failedFuture(new CryptoException("Encryption failed", e)); } @@ -81,7 +82,7 @@ public class CryptoUtil { } return secretKeyFuture.compose(secretKey -> { try { - byte[] decodedBytes = Base64.getDecoder().decode(strToDecrypt); + byte[] decodedBytes = Base64Decoder.decode(strToDecrypt); // Extract IV from the beginning of the decoded bytes ByteBuffer byteBuffer = ByteBuffer.wrap(decodedBytes); diff --git a/web-service/src/test/java/cn/qaiu/lz/common/util/Base64CompatibilityTest.java b/web-service/src/test/java/cn/qaiu/lz/common/util/Base64CompatibilityTest.java new file mode 100644 index 0000000..0cc3471 --- /dev/null +++ b/web-service/src/test/java/cn/qaiu/lz/common/util/Base64CompatibilityTest.java @@ -0,0 +1,40 @@ +package cn.qaiu.lz.common.util; + +import org.junit.Test; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class Base64CompatibilityTest { + @Test + public void acceptsStoredPasswordHash() { + String password = "密码-test"; + String hash = PasswordUtil.hashPassword(password); + assertTrue(PasswordUtil.checkPassword(password, hash)); + assertFalse(PasswordUtil.checkPassword("wrong", hash)); + } + + @Test + public void acceptsJwtWithUnpaddedUrlSafePayload() { + String json = "{\"username\":\"下载用户\"}"; + String payload = Base64.getUrlEncoder().withoutPadding().encodeToString(json.getBytes(StandardCharsets.UTF_8)); + assertEquals("下载用户", JwtUtil.getUsernameFromToken("header." + payload + ".signature")); + } + + @Test + public void acceptsLegacyEncodedAuth() throws Exception { + String key = "0123456789abcdef"; + String json = "{\"authType\":\"cookie\",\"token\":\"compatibility-test\"}"; + String base64 = cn.qaiu.util.AESUtils.encryptBase64ByAES(json, key); + String urlEncoded = URLEncoder.encode(base64, StandardCharsets.UTF_8); + assertEquals("cookie", AuthParamCodec.decode(urlEncoded, key).getAuthType()); + assertEquals("cookie", AuthParamCodec.decode(base64.replace('+', ' '), key).getAuthType()); + assertNull(AuthParamCodec.decode(base64 + "!", key)); + } +}