Skip to content

Commit db864c2

Browse files
committed
feat:去掉不需要的示例和注释
1 parent 2866e4f commit db864c2

File tree

5 files changed

+6
-249
lines changed

5 files changed

+6
-249
lines changed

volcengine-java-sdk-ark-runtime/src/main/java/com/volcengine/ark/runtime/interceptor/EncryptionInterceptor.java

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -57,26 +57,21 @@ public Response intercept(Chain chain) throws IOException {
5757
return chain.proceed(request);
5858
}
5959

60-
// 读取并解析请求体
6160
Map<String, Object> requestBodyJson = parseRequestBody(originalBody);
6261
String model = requestBodyJson.get("model").toString();
6362

64-
// 非加密模式直接处理
6563
if (!"true".equals(is_encrypt)) {
6664
return proceedWithoutEncryption(chain, request, requestBodyJson);
6765
}
6866

69-
// 加密模式处理
7067
return proceedWithEncryption(chain, request, requestBodyJson, model);
7168
}
7269

7370
private Response proceedWithEncryption(Chain chain, Request request, Map<String, Object> requestBodyJson, String model) throws IOException {
74-
// 获取服务器证书信息
7571
CertificateManager.ServerCertificateInfo certInfo = getServerCertificate(this.apiKey, this.baseUrl, model);
7672
if (certInfo == null) {
7773
throw new IOException("Failed to get server certificate for encryption");
7874
}
79-
// 生成会话密钥和令牌
8075
SessionData sessionData;
8176
try {
8277
sessionData = KeyAgreementUtil.generateEciesKeyPair(certInfo.getPublicKey());
@@ -86,26 +81,22 @@ private Response proceedWithEncryption(Chain chain, Request request, Map<String,
8681
byte[] e2eKey = sessionData.getCryptoKey();
8782
byte[] e2eNonce = sessionData.getCryptoNonce();
8883
String sessionToken = sessionData.getSessionToken();
89-
// 加密请求体
9084
RequestBody encryptedBody = encryptRequestBody(requestBodyJson, e2eKey, e2eNonce);
9185

9286
Request.Builder requestBuilder = request.newBuilder()
9387
.method(request.method(), encryptedBody);
9488

95-
// 添加AICC加密头信息
9689
addAiccEncryptionHeader(requestBuilder, certInfo);
9790

9891
requestBuilder.addHeader("X-Session-Token", sessionToken);
9992
Request encryptedRequest = requestBuilder.build();
10093

10194
Response originalResponse = chain.proceed(encryptedRequest);
10295

103-
// 处理失败响应
10496
if (!originalResponse.isSuccessful()) {
10597
return handleErrorResponse(originalResponse);
10698
}
10799

108-
// 解密成功响应
109100
return decryptResponse(e2eKey, e2eNonce, originalResponse);
110101
}
111102

@@ -179,10 +170,8 @@ private Map<String, Object> processMessage(Map<String, Object> message, byte[] e
179170
*/
180171
private Object processMessageContent(Object content, byte[] e2eKey, byte[] e2eNonce) throws IOException {
181172
if (content instanceof String) {
182-
// text
183173
return encryptStringWithKey(e2eKey, e2eNonce, (String) content);
184174
} else if (content instanceof Iterable) {
185-
// multiParts
186175
List<Object> processedParts = new ArrayList<>();
187176
for (Object part : (Iterable<?>) content) {
188177
if (part instanceof Map) {
@@ -207,10 +196,8 @@ private Map<String, Object> processContentPart(Map<String, Object> part, byte[]
207196

208197
switch (type) {
209198
case "text":
210-
// 加密文本
211199
part.put("text", encryptStringWithKey(e2eKey, e2eNonce, part.get("text").toString()));
212200
break;
213-
214201
case "image_url":
215202
@SuppressWarnings("unchecked")
216203
Map<String, Object> imageUrl = (Map<String, Object>) part.get("image_url");
@@ -233,7 +220,6 @@ private void processImageUrl(Map<String, Object> imageUrl, byte[] e2eKey, byte[]
233220
URI uri = new URI(url);
234221
String scheme = uri.getScheme();
235222
if ("data".equals(scheme)) {
236-
// 加密data URL
237223
imageUrl.put("url", encryptStringWithKey(e2eKey, e2eNonce, url));
238224
} else if ("http".equals(scheme) || "https".equals(scheme)) {
239225
System.err.println("encryption is not supported for image url, please use base64 image if you want encryption");
@@ -243,7 +229,6 @@ private void processImageUrl(Map<String, Object> imageUrl, byte[] e2eKey, byte[]
243229

244230
} catch (URISyntaxException e) {
245231
if (url.startsWith("data:")) {
246-
// 加密data URL
247232
imageUrl.put("url", encryptStringWithKey(e2eKey, e2eNonce, url));
248233
} else {
249234
throw new IOException("Invalid image URL format: " + url, e);
@@ -360,7 +345,7 @@ private Response handleNormalResponse(byte[] key, byte[] nonce, Response respons
360345
}
361346
}
362347

363-
String modifiedResponseBodyStr = mapper.writeValueAsString(responseJson);
348+
String decryptedContent = mapper.writeValueAsString(responseJson);
364349
ResponseBody originalResponseBody = response.body();
365350
MediaType contentType = null;
366351
if (originalResponseBody != null) {
@@ -371,7 +356,7 @@ private Response handleNormalResponse(byte[] key, byte[] nonce, Response respons
371356
}
372357
ResponseBody decryptedBody = ResponseBody.create(
373358
contentType,
374-
modifiedResponseBodyStr.getBytes(StandardCharsets.UTF_8)
359+
decryptedContent.getBytes(StandardCharsets.UTF_8)
375360
);
376361

377362
return response.newBuilder()

volcengine-java-sdk-ark-runtime/src/main/java/com/volcengine/ark/runtime/service/ArkService.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,6 @@ public ArkService build() {
523523
clientBuilder.dispatcher(dispatcher);
524524
}
525525

526-
// 重新配置clientBuilder,添加加密拦截器
527526
OkHttpClient client = clientBuilder
528527
.addInterceptor(new RequestIdInterceptor())
529528
.addInterceptor(new RetryInterceptor(retryTimes))

volcengine-java-sdk-ark-runtime/src/main/java/com/volcengine/ark/runtime/service/CertificateManager.java

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import java.util.regex.Pattern;
2424

2525
public class CertificateManager {
26-
// 证书缓存
2726
private static final ConcurrentHashMap<String, ServerCertificateInfo> certificateCache = new ConcurrentHashMap<>();
2827

2928
/**
@@ -87,7 +86,6 @@ public static ServerCertificateInfo getServerCertificateFromCache(String ep) {
8786
}
8887

8988
public static ServerCertificateInfo getServerCertificate(String apiKey, String baseUrl, String ep) throws IOException {
90-
// 首先检查内存缓存,用ep作为key
9189
if (hasCertificateInCache(ep)) {
9290
return getServerCertificateFromCache(ep);
9391
}
@@ -98,18 +96,13 @@ public static ServerCertificateInfo getServerCertificate(String apiKey, String b
9896

9997
String certificate;
10098

101-
// 1. 首先尝试从本地文件加载证书
10299
certificate = loadCertificateLocally(ep);
103100
if (certificate != null) {
104101
return createCertificateInfo(certificate, ep);
105102
}
106103

107-
// 2. 使用API Key方式获取证书
108-
else {
109-
certificate = loadCertificateByApiKey(baseUrl, apiKey, ep, aiccEnabled);
110-
}
104+
certificate = loadCertificateByApiKey(baseUrl, apiKey, ep, aiccEnabled);
111105

112-
// 保存证书到本地缓存
113106
saveCertificateLocally(ep, certificate);
114107

115108
return createCertificateInfo(certificate, ep);
@@ -121,7 +114,6 @@ public static ServerCertificateInfo getServerCertificate(String apiKey, String b
121114

122115
public static String[] getCertInfo(String certPem) {
123116
try {
124-
// 使用try-with-resources自动管理PEMParser资源
125117
try (PEMParser pemParser = new PEMParser(new StringReader(certPem))) {
126118
Object object = pemParser.readObject();
127119

@@ -141,16 +133,15 @@ public static String[] getCertInfo(String certPem) {
141133

142134
if (ringPattern.matcher(firstDns).matches() &&
143135
keyPattern.matcher(secondDns).matches()) {
144-
String ringId = firstDns.substring(5); // ring. 5个字符
145-
String keyId = secondDns.substring(4); // key. 4个字符
136+
String ringId = firstDns.substring(5);
137+
String keyId = secondDns.substring(4);
146138
return new String[]{ringId, keyId};
147139
}
148140
}
149141
}
150142
}
151143
}
152144
} catch (Exception e) {
153-
// 异常处理
154145
throw new RuntimeException("Failed to parse certificate to get ring_id and key_id", e);
155146
}
156147
return new String[]{"", ""};
@@ -167,23 +158,19 @@ public static String loadCertificateLocally(String ep) throws IOException {
167158
File certFile = new File(certFilePath);
168159

169160
if (certFile.exists()) {
170-
// 检查证书是否过期(是否超过14天)
171161
long lastModifiedSeconds = certFile.lastModified() / 1000;
172162
long currentTimeSeconds = System.currentTimeMillis() / 1000;
173163
long timeDifferenceSeconds = currentTimeSeconds - lastModifiedSeconds;
174-
long certExpirationSeconds = 14L * 24 * 60 * 60; // 14天,以秒为单位
164+
long certExpirationSeconds = 14L * 24 * 60 * 60;
175165
if (timeDifferenceSeconds <= certExpirationSeconds) {
176166
String certPem = new String(java.nio.file.Files.readAllBytes(certFile.toPath()), StandardCharsets.UTF_8);
177167

178-
// 检查证书是否完整(与AICC/PCA兼容性检查)
179168
String[] certInfo = getCertInfo(certPem);
180169
String ringId = certInfo[0];
181170
String keyId = certInfo[1];
182171

183172
boolean aiccEnabled = "AICC".equals(System.getenv("VOLC_ARK_ENCRYPTION"));
184173

185-
// 1. 非AICC模式:即使ring或key为空也可以接受
186-
// 2. AICC模式:ring和key都必须不为空
187174
if ((ringId.isEmpty() || keyId.isEmpty()) && !aiccEnabled) {
188175
return certPem;
189176
}
@@ -192,7 +179,6 @@ public static String loadCertificateLocally(String ep) throws IOException {
192179
}
193180
}
194181

195-
// 证书过期或不满足条件,删除文件
196182
certFile.delete();
197183
}
198184
} catch (Exception e) {
@@ -346,7 +332,6 @@ public static void saveCertificateLocally(String ep, String certificate) throws
346332
String certStoragePath = getCertStoragePath();
347333
String certFilePath = certStoragePath + File.separator + ep + ".pem";
348334

349-
// 确保目录存在
350335
File storageDir = new File(certStoragePath);
351336
if (!storageDir.exists()) {
352337
if (!storageDir.mkdirs()) {
@@ -355,7 +340,6 @@ public static void saveCertificateLocally(String ep, String certificate) throws
355340
}
356341
}
357342

358-
// 写入证书文件
359343
java.nio.file.Files.write(
360344
Paths.get(certFilePath),
361345
certificate.getBytes(StandardCharsets.UTF_8)
@@ -387,15 +371,12 @@ public static void cacheServerCertificate(String cacheKey, PublicKey publicKey,
387371
*/
388372
public static PublicKey extractPublicKeyFromCertificate(String certificate) throws GeneralSecurityException {
389373
try {
390-
// 移除PEM头尾
391374
String certContent = certificate.replace("-----BEGIN CERTIFICATE-----", "")
392375
.replace("-----END CERTIFICATE-----", "")
393376
.replaceAll("\\s", "");
394377

395-
// 解码Base64
396378
byte[] certBytes = Base64.getDecoder().decode(certContent);
397379

398-
// 解析证书
399380
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
400381
X509Certificate x509Cert = (X509Certificate) certFactory.generateCertificate(
401382
new java.io.ByteArrayInputStream(certBytes));
@@ -420,7 +401,6 @@ public static ServerCertificateInfo createCertificateInfo(String certificate, St
420401
ServerCertificateInfo certInfo =
421402
new ServerCertificateInfo(publicKey, ringId, keyId);
422403

423-
// 缓存到内存
424404
cacheServerCertificate(ep, publicKey, ringId, keyId);
425405

426406
return certInfo;

volcengine-java-sdk-ark-runtime/src/main/java/com/volcengine/ark/runtime/utils/KeyAgreementUtil.java

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,9 @@
2727
*/
2828
public class KeyAgreementUtil {
2929
static {
30-
// 注册Bouncy Castle提供者
3130
Security.addProvider(new BouncyCastleProvider());
3231
}
3332

34-
// 算法常量
3533
private static final String HKDF_ALGORITHM = "HmacSHA256";
3634

3735
/**
@@ -104,7 +102,6 @@ public static SessionData generateEciesKeyPair(PublicKey publicKey) throws Gener
104102
*/
105103
public static byte[] hkdf(byte[] sharedSecret, byte[] salt, byte[] info, int length)
106104
throws GeneralSecurityException {
107-
// 提取阶段
108105
Mac hmacExtract = Mac.getInstance(HKDF_ALGORITHM);
109106
if (salt == null) {
110107
salt = new byte[32];
@@ -113,7 +110,6 @@ public static byte[] hkdf(byte[] sharedSecret, byte[] salt, byte[] info, int len
113110
hmacExtract.init(saltKey);
114111
byte[] prk = hmacExtract.doFinal(sharedSecret);
115112

116-
// 扩展阶段
117113
Mac hmacExpand = Mac.getInstance(HKDF_ALGORITHM);
118114
SecretKeySpec prkKey = new SecretKeySpec(prk, HKDF_ALGORITHM);
119115
hmacExpand.init(prkKey);
@@ -318,7 +314,6 @@ public static String aesGcmDecryptBase64List(byte[] key, byte[] nonce, String ci
318314
String decrypted = aesGcmDecryptBase64String(key, nonce, b64);
319315
result.add(decrypted);
320316
} catch (Exception e) {
321-
// 调用递归解密方法
322317
String cornerCaseResult = decryptCornerCase(key, nonce, b64);
323318
result.add(cornerCaseResult);
324319
}
@@ -368,7 +363,6 @@ private static String decryptCornerCase(byte[] key, byte[] nonce, String data) {
368363
continue;
369364
}
370365
}
371-
// 如果所有尝试都失败,返回空字符串
372366
return "";
373367
}
374368
}

0 commit comments

Comments
 (0)