Skip to content

Instantly share code, notes, and snippets.

@muminc
Created July 23, 2019 00:39
Show Gist options
  • Save muminc/35836325d1c97c7c2ab6eb368ef2091f to your computer and use it in GitHub Desktop.
Save muminc/35836325d1c97c7c2ab6eb368ef2091f to your computer and use it in GitHub Desktop.
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.PrivateKeyDetails;
import org.apache.http.ssl.PrivateKeyStrategy;
import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.SSLContext;
import java.net.Socket;
import java.security.KeyStore;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
public class TestRun {
public static void main(String[] args) {
KeyStore windowsMyKeyStore = null;
try {
windowsMyKeyStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
windowsMyKeyStore.load(null,new char[]{});
SSLContext sslContext = SSLContexts.custom().loadKeyMaterial(windowsMyKeyStore, null, new PrivateKeyStrategy() {
@Override
public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
for (String alias : aliases.keySet()) {
PrivateKeyDetails privateKeyDetails = aliases.get(alias);
for (X509Certificate certificate : privateKeyDetails.getCertChain()) {
try {
certificate.checkValidity();
List<String> extKeyUsage = certificate.getExtendedKeyUsage();
if (extKeyUsage != null && extKeyUsage.contains("1.3.6.1.5.5.7.3.2"))
return alias;
} catch (CertificateExpiredException | CertificateNotYetValidException | CertificateParsingException e) {
continue;
}
}
}
return null;
}
}).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1.2", "TLSv1.1"},
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
CloseableHttpClient build = HttpClients.custom()
.setSSLSocketFactory(sslConnectionSocketFactory)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
HttpGet request = new HttpGet("https://localhost:8443");
CloseableHttpResponse execute = build.execute(request);
System.out.println("execute = " + execute.getEntity().getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment