2015年6月20日土曜日
Javaでクライアント認証の読込み
Javaでクライアント認証を読込み PKCS#12
証明書は以下を見て作るとよい
http://server-setting.info/centos/apache-ssl-auth-setting.html
下記は、だいたいこんな感じぐらいで
環境を忘れて確認できなくなったので間違っているかも。。。。。
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
public class App
{
static final String P12FILE = "cert.p12";
static final char[] PASSWORD = "pass".toCharArray();
private static SSLContext getSslContext() {
// PKCS12ファイル読み込み
KeyManagerFactory keyManagerFactory;
try (FileInputStream inputStream = new FileInputStream(P12FILE)) {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(inputStream, PASSWORD);
keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, PASSWORD);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
return sslContext;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception {
int socketTimeout = 60000;
int connectionTimeout = 60000;
String userAgent = "My Http Client 0.1";
// request configuration
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(connectionTimeout)
.setSocketTimeout(socketTimeout)
.build();
// headers
List<Header> headers = new ArrayList<Header>();
headers.add(new BasicHeader("Accept-Charset", "utf-8"));
headers.add(new BasicHeader("Accept-Language", "ja, en;q=0.8"));
headers.add(new BasicHeader("User-Agent", userAgent));
// create client
HttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setDefaultHeaders(headers).setSSLContext(getSslContext())
.build();
HttpGet httpGet = new HttpGet("https://mixi.jp/");
HttpResponse response = httpClient.execute(httpGet);
int responseStatus = response.getStatusLine().getStatusCode();
String body = EntityUtils.toString(response.getEntity(), "UTF-8");
System.out.println(body);
}
}
登録:
投稿 (Atom)