サンプルといっても完成形ではないが。。。
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.net.http.HttpClient; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate;
try{ SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{ new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } }}, new SecureRandom()); SSLSocketFactory sslSocketFactory = (javax.net.ssl.SSLSocketFactory)SSLSocketFactory.getDefault(); HttpClient client = HttpClient.newBuilder() .sslContext(sslContext) .build(); // TODO HttpRequest を作って送信 }catch (NoSuchAlgorithmException e){ e.printStackTrace(); }catch (KeyManagementException e){ e.printStackTrace(); }
本来、JKS形式キーストア形式の鍵ファイルとパスワードで
SSLContextを作るべきで、
private static SSLContext getSSLContext(String keyFilePath, String pass) throws KeyManagementException, KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException { // KeyStore KeyStore clientStore = KeyStore.getInstance("jks"); // 指定された入力ストリームからこのキーストアをロード FileInputStream keyFileStream = new FileInputStream(keyFilePath); clientStore.load(keyFileStream, pass.toCharArray()); keyFileStream.close(); // KeyManager KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, pass.toCharArray()); // 鍵データの種類ごとに 1 つの鍵マネージャーを取得 KeyManager[] kms = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(kms, null, new SecureRandom()); return sslContext; }
のようなメソッドを用意してSSLContextを指定すべきなのであろう。