您好,我找不到解决方案,如何使用我的证书来签署 REST API 请求,以进行双向握手?
我的代码:
HttpUrl.Builder httpUrlBuilder = httpUrl.newBuilder();
Request.Builder builder = new Request.Builder()
.url(httpUrlBuilder.build())
.post(okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), body));
for (Map.Entry<String, String> header : headers.entrySet()) {
builder.addHeader(header.getKey(), header.getValue());
}
Request request = builder.build();
OkHttpClient httpClient = new OkHttpClient.Builder().sslSocketFactory(SSLContext.getDefault().getSocketFactory()).build();
Response response = httpClient.newCall(request).execute();
String res = response.body().string();
System.out.print("Response: " +res);
我使用 SpringBoot 框架,证书加载方式:
server.ssl.key-store=certFile.pfx
server.ssl.key-store-password=****
server.ssl.keyStoreType=PKCS12
security.require-ssl=true
此代码工作正常,但没有证书签名对我来说毫无用处
使用:
private String submitPostRequest(String url, Map<String, String> headers, String body) throws Exception {
OkHttpClient client = createOkHttpClient(pfxCert, pfxCertPass);
RequestBody requestBody = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), body);
Request.Builder builder = new Request.Builder()
.url(url)
.post(requestBody);
for (Map.Entry<String, String> header : headers.entrySet()) {
builder.addHeader(header.getKey(), header.getValue());
}
Request request = builder.build();
try (Response response = client.newCall(request).execute()) {
String responseContent = response.body().string();
System.out.println(response.code());
System.out.println("Server response: " + responseContent);
return responseContent;
}
}
方法:
private static OkHttpClient createOkHttpClient(String pfxFilePath, String pfxPassword) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (FileInputStream pfxInputStream = new FileInputStream(pfxFilePath)) {
keyStore.load(pfxInputStream, pfxPassword.toCharArray());
}
SSLContext sslContext = SSLContext.getInstance("TLS");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, pfxPassword.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagerFactory.getTrustManagers()[0]);
return builder.build();
}