10
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RestTemplate オレオレ証明書でSSL通信する httpclient 4.5.2ver

Last updated at Posted at 2016-10-18

専用回線引いてるくせに、セキュリティを重視してSSLで通信して下さいと言われた。
でも、なぜか証明書はオレオレ証明で・・・・・なんかSSLの意味がないような・・・。
ということで、ネットに比較的新しい実装例がなかったのでここに備忘録として残しておく。

public RestTemplate restTemplate(){

		//httpclient	: '4.5.2

		final String keyStoreType = "PKCS12";
		final String keyStorePath = "../../keyStore.p12";
		final String keyStorePassWord = "password";
		final String sslProtoCol = "TLSv1.2";


		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

		// keyStoreのロード
		KeyStore keyStore = KeyStore.getInstance(keyStoreType);
		keyStore.load(new FileInputStream(keyStorePath), keyStorePassWord.toCharArray());

		// KeyManagerの設定
		KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		kmf.init(keyStore, keyStorePassWord.toCharArray());

		// SSLContextの生成
		SSLContext sslContext = SSLContext.getInstance(sslProtoCol);
		sslContext.init(kmf.getKeyManagers(),
				new X509TrustManager[]{ new LooseTrustManger()},
				new SecureRandom());

		httpClientBuilder.setSSLContext(sslContext);

		// 証明書のホストの検証を無視する
		httpClientBuilder.setSSLHostnameVerifier(new LooseHostnameVerrifer());

		HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
		factory.setHttpClient(httpClientBuilder.build());

		return new RestTemplate(factory);

	}

public class LooseTrustManger implements X509TrustManager{

	/**
	 * 検証を何もしない
	 */
	@Override
	public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

	/**
	 * 検証を何もしない
	 */
	@Override
	public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}

	/**
	 * 証明書を返却しない
	 */
	@Override
	public X509Certificate[] getAcceptedIssuers() {return null;}

}

public class LooseHostnameVerrifer implements HostnameVerifier{

	@Override
	public boolean verify(String arg0, SSLSession arg1) {return true;}

}

こんな感じで、javaのkeytoolで作成したオレオレ証明書で通信できました。
findbagusにかけたら警告がでちゃいますが気にしない。

10
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?