mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-25 06:47:00 +00:00
Merge pull request #296 from qaiu/fix/java4shell-base64
fix: 缓解 Java4Shell(CVE-2026-114938)
This commit is contained in:
25 files changed
+592
-51
No files matched your search
@@ -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'
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
FROM eclipse-temurin:17-jre
|
||||
ARG JAVA_RUNTIME_IMAGE=eclipse-temurin:17-jre
|
||||
FROM ${JAVA_RUNTIME_IMAGE}
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
Regular → Executable
+5
-1
@@ -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" "$@"
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
+9
-1
@@ -165,6 +165,10 @@
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<release>${maven.compiler.source}</release>
|
||||
<compilerArgs>
|
||||
<arg>--add-modules</arg>
|
||||
<arg>jdk.incubator.vector</arg>
|
||||
</compilerArgs>
|
||||
<encoding>${project.build.sourceEncoding}</encoding>
|
||||
</configuration>
|
||||
</plugin>
|
||||
@@ -200,7 +204,11 @@
|
||||
<!-- 忽略 Javadoc 错误 -->
|
||||
<failOnError>false</failOnError>
|
||||
<!-- 禁用 doclint(新版参数名改为 additionalOptions) -->
|
||||
<additionalOptions>-Xdoclint:none</additionalOptions>
|
||||
<additionalOptions>
|
||||
<additionalOption>-Xdoclint:none</additionalOption>
|
||||
<additionalOption>--add-modules</additionalOption>
|
||||
<additionalOption>jdk.incubator.vector</additionalOption>
|
||||
</additionalOptions>
|
||||
<!-- 如果项目源码中几乎没有 Javadoc,可设 true -->
|
||||
<quiet>true</quiet>
|
||||
</configuration>
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
|
||||
|
||||
@@ -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<String> 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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 -> {
|
||||
|
||||
@@ -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<String, String> 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) { // 文件
|
||||
|
||||
@@ -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解密========================================== //
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
* <p>不再做 URLEncoder,避免前端/代理再 encode 时变成 %253D。</p>
|
||||
*/
|
||||
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) {
|
||||
|
||||
@@ -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<Byte> SPECIES = ByteVector.SPECIES_PREFERRED;
|
||||
private static final int WIDTH = SPECIES.length();
|
||||
private static final int PACKED = WIDTH / 4 * 3;
|
||||
private static final VectorMask<Byte> PACKED_MASK = SPECIES.indexInRange(0, PACKED);
|
||||
// Each four-byte lane holds one quartet. Pack or expand its three binary bytes.
|
||||
private static final VectorShuffle<Byte> PACK = VectorShuffle.fromOp(SPECIES,
|
||||
i -> i < PACKED ? i / 3 * 4 + i % 3 : 0);
|
||||
private static final VectorShuffle<Byte> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<String, byte[]> 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));
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,7 @@
|
||||
<jackson.version>2.18.9</jackson.version>
|
||||
<!-- Logback 最新稳定版 -->
|
||||
<logback.version>1.5.34</logback.version>
|
||||
<skipTests>true</skipTests>
|
||||
<junit.version>4.13.2</junit.version>
|
||||
</properties>
|
||||
|
||||
@@ -97,7 +98,7 @@
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.2</version>
|
||||
<configuration>
|
||||
<skipTests>true</skipTests>
|
||||
<skipTests>${skipTests}</skipTests>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
@@ -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解密
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user