Skip to content

Commit c7e8086

Browse files
committed
baichuan update
1 parent 218222a commit c7e8086

1 file changed

Lines changed: 32 additions & 7 deletions

File tree

chat2db-server/chat2db-server-web/chat2db-server-web-api/src/main/java/ai/chat2db/server/web/api/controller/ai/baichuan/interceptor/BaichuanHeaderAuthorizationInterceptor.java

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import lombok.Getter;
66
import lombok.extern.slf4j.Slf4j;
77
import okhttp3.*;
8+
import okio.Buffer;
89

910
import java.io.IOException;
1011
import java.nio.charset.StandardCharsets;
@@ -39,26 +40,50 @@ public Response intercept(Chain chain) throws IOException {
3940
// 获取当前的时间戳(UTC标准时间戳)
4041
long timestamp = System.currentTimeMillis() / 1000;
4142

42-
// 构造 HTTP-Body,这里需要根据实际情况构造你的请求体
43-
// 这里示例构造一个空的请求体
44-
RequestBody requestBody = RequestBody.create("", MediaType.parse("text/plain"));
43+
// 获取原始的HTTP-Body
44+
RequestBody originalRequestBody = originalRequest.body();
45+
Buffer buffer = new Buffer();
46+
if (originalRequestBody != null) {
47+
originalRequestBody.writeTo(buffer);
48+
}
49+
String httpBody = buffer.readUtf8();
4550

4651
// 计算 X-BC-Signature
47-
String signature = calculateSignature(secretKey, requestBody, timestamp);
52+
String signature = calculateSignature(secretKey, httpBody, timestamp);
4853

4954
// 创建新的请求,并添加自定义请求头
5055
Request newRequest = originalRequest.newBuilder()
51-
.addHeader(Header.AUTHORIZATION.getValue(), "Bearer " + apiKey)
52-
.addHeader(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue())
56+
.addHeader("Authorization", "Bearer " + apiKey)
57+
.addHeader("Content-Type", "application/json")
5358
.addHeader("X-BC-Sign-Algo", "MD5")
5459
.addHeader("X-BC-Timestamp", String.valueOf(timestamp))
5560
.addHeader("X-BC-Signature", signature)
56-
.method(originalRequest.method(), originalRequest.body())
61+
.method(originalRequest.method(), RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), httpBody))
5762
.build();
5863

5964
return chain.proceed(newRequest);
6065
}
6166

67+
private String calculateSignature(String secretKey, String httpBody, long timestamp) {
68+
String toHash = secretKey + httpBody + timestamp;
69+
return md5(toHash);
70+
}
71+
72+
private String md5(String s) {
73+
try {
74+
MessageDigest digest = MessageDigest.getInstance("MD5");
75+
byte[] result = digest.digest(s.getBytes(StandardCharsets.UTF_8));
76+
StringBuilder sb = new StringBuilder();
77+
for (byte b : result) {
78+
sb.append(String.format("%02x", b));
79+
}
80+
return sb.toString();
81+
} catch (Exception e) {
82+
log.error("baichuan secret key md5 error", e);
83+
return "";
84+
}
85+
}
86+
6287
private String calculateSignature(String secretKey, RequestBody body, long timestamp) {
6388
try {
6489
String requestBody = bodyToString(body);

0 commit comments

Comments
 (0)