사용자가 만든 인증서로 인증 테스트

Java 2016.10.06 17:36

자바소스를 잘 정리한 페이지가 있어 링크를 남긴다.


참고 링크

http://tjjava.blogspot.kr/2012/03/https.html

http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html

http://www.java2s.com/Tutorial/Java/0490__Security/SSLContextandKeymanager.htm


위 링크에서 사용자가 만든 인증서로 인증하는 법만 정리 해보자.



작업 환경은 이클립스 + Maven Static Web Project 로 작업했다. 환경을 언급한 이유는 만들어 둔 인증서 파일의 경로를 맞추기 위해서인데, 인증서를 프로젝트 루트( / )에 넣어야 JAVA 실행 시에 읽어서 열 수 있다.

물론 전체 경로까지 전부 넣어주면 되겠으나 사람마다 다르니 프로젝트 루트에 넣어서 테스트하는게 편해보였다.


간단히 설명하자면, 테스트를 위해서는 서버와 클라이언트가 필요하다. 서버에서는 keystore를 이용하고 클라이언트에서는 truststore를 이용한다. 소스는 정상적으로 동작하는 것을 확인하였다. 


SimpleHttpsServer.java

import java.io.BufferedReader;  

import java.io.BufferedWriter;  

import java.io.FileInputStream;  

import java.io.IOException;  

import java.io.InputStream;  

import java.io.InputStreamReader;  

import java.io.OutputStream;  

import java.io.OutputStreamWriter;  

import java.security.KeyManagementException;  

import java.security.KeyStore;  

import java.security.KeyStoreException;  

import java.security.NoSuchAlgorithmException;  

import java.security.UnrecoverableKeyException;  

import java.security.cert.CertificateException;  

  

import javax.net.ssl.KeyManagerFactory;  

import javax.net.ssl.SSLContext;  

import javax.net.ssl.SSLServerSocket;  

import javax.net.ssl.SSLServerSocketFactory;  

import javax.net.ssl.SSLSocket;


public class SimpleHttpsServer {


/**

* 사용자가 만든 인증서 테스트 서버

* 대기하다가 요청에 대해 응답하고 종료한다.

* @param port

* @throws NoSuchAlgorithmException

* @throws KeyManagementException

* @throws IOException

* @throws KeyStoreException

* @throws CertificateException

* @throws UnrecoverableKeyException

*/

public void run(int port) throws NoSuchAlgorithmException, KeyManagementException, IOException, KeyStoreException, CertificateException, UnrecoverableKeyException {

// create ssl context

SSLContext context = SSLContext.getInstance("TLS");

// set key store

KeyStore keyStore = KeyStore.getInstance("JKS");

keyStore.load(new FileInputStream("keystore.jks"), "qwerty1234".toCharArray());  // 파일명, 비번

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

kmf.init(keyStore, "qwerty1234".toCharArray()); // keyStore, 비번

context.init(kmf.getKeyManagers(), null, null);

// create ssl socket

SSLServerSocketFactory factory = context.getServerSocketFactory();

SSLServerSocket socket = (SSLServerSocket)factory.createServerSocket(port);

SSLSocket client = (SSLSocket)socket.accept();

InputStream in = client.getInputStream();

OutputStream out = client.getOutputStream();

// read from client

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

reader.readLine();

// write to client

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));

writer.write("HTTP/1.0 200 OK");

writer.newLine();

writer.write("Content-Type: text/html");

writer.newLine();

writer.newLine();

writer.write("<html><head><title>Hello</title></head><body>Hellow!</body></html>");

writer.flush();

// close

writer.close();

reader.close();

client.close();

}

/**

* @param args

* @throws Exception

*/

public static void main(String[] args) throws Exception {

SimpleHttpsServer server = new SimpleHttpsServer();

server.run(9999);

}

}


HttpsClientWithCustomCert.java

import java.io.BufferedReader;  

import java.io.FileInputStream;  

import java.io.IOException;  

import java.io.InputStream;  

import java.io.InputStreamReader;  

import java.net.URL;  

import java.security.KeyManagementException;  

import java.security.KeyStore;  

import java.security.KeyStoreException;  

import java.security.NoSuchAlgorithmException;  

import java.security.cert.CertificateException;  

import java.security.cert.X509Certificate;  

  



import javax.net.ssl.HostnameVerifier;  

import javax.net.ssl.HttpsURLConnection;  

import javax.net.ssl.SSLContext;  

import javax.net.ssl.SSLSession;  

import javax.net.ssl.TrustManager;  

import javax.net.ssl.TrustManagerFactory;  

import javax.net.ssl.X509TrustManager;  


public class HttpsClientWithCustomCert {

/**

* 사용자가 만든 인증서 테스트 클라이언트

* @param urlString

* @throws IOException

* @throws NoSuchAlgorithmException

* @throws KeyManagementException

*/

public String getHttps(String urlString) throws IOException, NoSuchAlgorithmException, KeyManagementException {

// Get HTTPS URL connection

URL url = new URL(urlString);  

HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();

// Set Hostname verification

conn.setHostnameVerifier(new HostnameVerifier() {

public boolean verify(String hostname, SSLSession session) {

// Ignore host name verification. It always returns true.

return true;

}

});

// SSL setting

SSLContext context = SSLContext.getInstance("TLS");

context.init(null, new TrustManager[] { new X509TrustManager() {


public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

// client certification check

}


public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

// Server certification check

try {

// Get trust store

KeyStore trustStore = KeyStore.getInstance("JKS");

trustStore.load(new FileInputStream("truststore.jks"), "qwerty1234".toCharArray()); // Use default certification validation

// Get Trust Manager

TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

tmf.init(trustStore);

TrustManager[] tms = tmf.getTrustManagers();

((X509TrustManager)tms[0]).checkServerTrusted(chain, authType);

} catch (KeyStoreException e) {

e.printStackTrace();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}


public X509Certificate[] getAcceptedIssuers() {

return null;

}

} }, null);

conn.setSSLSocketFactory(context.getSocketFactory());

// Connect to host

conn.connect();

conn.setInstanceFollowRedirects(true);

// Print response from host

InputStream in = conn.getInputStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(in));

String page = "";

String line = null;

while ((line = reader.readLine()) != null) {  

page += line+"\n";  

}  

 

reader.close();

return page;

}

/**

* @param args

* @throws Exception

*/

public static void main(String[] args) throws Exception {

HttpsClientWithCustomCert test = new HttpsClientWithCustomCert();

String page = test.getHttps("https://127.0.0.1:9999");

System.out.println("==>"+page);

}

}




Trackback 0 : Comment 0

티스토리 툴바