java实现https双向认证

来源:互联网 发布:中国联通软件开发待遇 编辑:程序博客网 时间:2024/05/18 22:44

了解了一些https的工作原理,但是还是理解的不透彻,参考其他实现,写了一段代码练手。

参考文章:

1.讲https的工作原理的:Java 和 HTTP 的那些事(四) HTTPS 和 证书

2.keytool相关命令:使用keytool 生成证书

一些没有解决的疑惑:

1.单向认证的代码应该咋写?

2.这个代码是正确的双向认证吗?

3.证书必须与域名绑定吗?(为什么证书要与域名绑定)

4.通配符形式的域名的证书怎么生成?



httpsServer:

import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.InetSocketAddress;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 java.util.HashMap;import java.util.concurrent.LinkedBlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import javax.net.ssl.KeyManagerFactory;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManagerFactory;import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;import com.sun.net.httpserver.HttpsConfigurator;import com.sun.net.httpserver.HttpsServer;public class Test_httpsServer {public static ThreadPoolExecutor httpExecutor = new ThreadPoolExecutor(20, 100, 60, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(800));public static HttpsServer httpsServer;public static void main(String args[]) throws IOException {try {httpsServer = HttpsServer.create(new InetSocketAddress(9000), 100);httpExecutor.allowCoreThreadTimeOut(true);httpsServer.setExecutor(httpExecutor);//如果采用http注释掉这一行setSSLContext(httpsServer);httpsServer.createContext("/", new HttpHandler() {public void handle(HttpExchange exchange) throws IOException {String query = exchange.getRequestURI().getRawQuery();ByteArrayOutputStream baos = new ByteArrayOutputStream();copy(exchange.getRequestBody(), baos);String data = baos.toString();System.out.println("received a new request.");System.out.println("query:" + query);System.out.println("data:" + data);HashMap<String, String> parameters = new HashMap<String, String>();if (query != null && !query.equals("")) {String[] paras = query.split("\\&");for (String para : paras) {String[] array = para.split("\\=");if (array.length == 2) {parameters.put(array[0], array[1]);}}}System.out.println(parameters);System.out.println();exchange.sendResponseHeaders(200, 0);OutputStream out = exchange.getResponseBody();String response = "<html><body>hello,welcome to this place.</body></html>";out.write(response.getBytes());out.close();exchange.close();}});httpsServer.start();System.out.println("start server sucessfully!");} catch (Exception e) {e.printStackTrace();}}public static void setSSLContext(HttpsServer httpsServer) {String serverKeyStoreFile = "C:/Users/copbint/Desktop/testKeys/server.keystore";String serverKeyStorePwd = "123456";String serverKeyPwd = "123456";String serverTrustKeyStoreFile = "C:/Users/copbint/Desktop/testKeys/server_trust.keystore";String serverTrustKeyStorePwd = "123456";try {KeyStore serverKeyStore = KeyStore.getInstance("JKS");serverKeyStore.load(new FileInputStream(serverKeyStoreFile), serverKeyStorePwd.toCharArray());KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());keyManagerFactory.init(serverKeyStore, serverKeyPwd.toCharArray());KeyStore serverTrustKeyStore = KeyStore.getInstance("JKS");serverTrustKeyStore.load(new FileInputStream(serverTrustKeyStoreFile), serverTrustKeyStorePwd.toCharArray());TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init(serverTrustKeyStore);SSLContext sslContext = SSLContext.getInstance("SSLv3");sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));} catch (KeyStoreException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (CertificateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (UnrecoverableKeyException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (KeyManagementException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static void copy(InputStream in, OutputStream out) throws IOException {byte[] buffer = new byte[512];int n = -1;while ((n = in.read(buffer)) != -1) {out.write(buffer, 0, n);}}}


httpsClient:

import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.URI;import java.net.URL;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.HttpsURLConnection;import javax.net.ssl.KeyManagerFactory;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManagerFactory;public class Test_httpsClient {public static void main(String args[]) throws IOException {SSLSocketFactory sslSocketFactory = getSslSocketFactory();try {String query = "name=whoAmI";byte[] input = "hello,I want to talk with you.".getBytes();URL url = new URI("https", null, "localhost", 9000, "/index.html", query, null).toURL();//URL url = new URI("http", null, "localhost", 9000, "/index.html", query, null).toURL();System.out.println(url);HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();//如果用http注释掉这一行connection.setSSLSocketFactory(sslSocketFactory);connection.setRequestMethod("GET");connection.setRequestProperty("connection", "Keep-Alive");connection.setDoOutput(input != null);if (input != null) {OutputStream out = connection.getOutputStream();out.write(input);out.flush();out.close();}ByteArrayOutputStream baos = new ByteArrayOutputStream();InputStream in = connection.getInputStream();copy(in, baos);System.out.println("status:" + connection.getResponseCode());System.out.println("data:" + baos.toString());} catch (Exception e) {e.printStackTrace();}}public static SSLSocketFactory getSslSocketFactory() {String clientKeyStoreFile = "C:/Users/copbint/Desktop/testKeys/client.keystore";String clientKeyStorePwd = "123456";String clientKeyPwd = "123456";String clientTrustKeyStoreFile = "C:/Users/copbint/Desktop/testKeys/client_trust.keystore";String clientTrustKeyStorePwd = "123456";try {KeyStore clientKeyStore = KeyStore.getInstance("JKS");clientKeyStore.load(new FileInputStream(clientKeyStoreFile), clientKeyStorePwd.toCharArray());KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());keyManagerFactory.init(clientKeyStore, clientKeyPwd.toCharArray());KeyStore clientTrustKeyStore = KeyStore.getInstance("JKS");clientTrustKeyStore.load(new FileInputStream(clientTrustKeyStoreFile), clientTrustKeyStorePwd.toCharArray());TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());trustManagerFactory.init(clientTrustKeyStore);SSLContext sslContext = SSLContext.getInstance("SSLv3");sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);return sslContext.getSocketFactory();} catch (KeyStoreException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (CertificateException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (UnrecoverableKeyException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();}return null;}public static void copy(InputStream in, OutputStream out) throws IOException {byte[] buffer = new byte[512];int n = -1;while ((n = in.read(buffer)) != -1) {out.write(buffer, 0, n);}in.close();out.close();}}



原创粉丝点击