package com.jinhill.net;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.security.KeyStore;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
public class SSLClient {
//受信任根证书库
private String mTrustStore = "C:/Documents and Settings/bo.chen/.keystore";
private String mTrustStorePwd = "123456";
//客户端证书库,这里采用PFX格式
private String mClientKeyStore = "C:/cb.pfx";
private String mClientKeyStorePwd = "123456";
public SSLClient(){
//设置受任根证库
System.setProperty("javax.net.ssl.trustStore", mTrustStore);
//System.setProperty("javax.net.ssl. trustStorePassword", mTrustStorePwd);
//System.setProperty("javax.net.debug", "ssl,handshake");
}
public void setTrustStore(String trustStore, String trustStorePwd){
mTrustStore = trustStore;
mTrustStorePwd = trustStorePwd;
}
public void setClientStore(String clientKeyStore, String clientKeyStorePwd){
mClientKeyStore = clientKeyStore;
mClientKeyStorePwd = clientKeyStorePwd;
}
//SSL单向认证连接
private Socket ConnectWithoutCert(String host, int port) throws Exception {
SocketFactory sf = SSLSocketFactory.getDefault();
Socket s = sf.createSocket(host, port);
return s;
}
//SSL双向认证连接
private Socket ConnectWithCert(String host, int port) throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(mClientKeyStore), mClientKeyStorePwd.toCharArray());
KeyManagerFactory kf = KeyManagerFactory.getInstance("SunX509");
kf.init(ks, mClientKeyStorePwd.toCharArray());
//如果不System.setProperty("javax.net.ssl.trustStore", mTrustStore);
//也可以用下列方法动态进行受信任根证书设置
/*
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore tks = KeyStore.getInstance("JKS");
tks.load(new FileInputStream(mTrustStore), mTrustStorePwd.toCharArray());
tmf.init(tks);
context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null);
*/
context.init(kf.getKeyManagers(), null, null);
SocketFactory factory = context.getSocketFactory();
Socket s = factory.createSocket(host, port);
return s;
}
public static void main(String[] args) throws Exception {
//HTTP请求
String request = "GET / HTTP/1.1\r\nHost: www.jinhill.com\r\nConnection: Keep-Alive\r\nUser-Agent: Java Client Tool\r\n\r\n";
String receive = "RECV:";
int len = 0;
SSLClient client = new SSLClient();
//连接SSL服务器
Socket s = client.ConnectWithCert("www.jinhill.com", 443);
//Socket s = client.ConnectWithoutCert("www.jinhill.com", 443);
//设置输入输出流
OutputStream os = s.getOutputStream();
InputStream is = s.getInputStream();
//发送HTTP请求
os.write(request.getBytes());
os.flush();
//读取HTTP响应数据
while(true){
byte[] buf = new byte[1024];
len = is.read(buf);
receive += (new String(buf));
if(len < 1024)
{
break;
}
}
System.out.println(receive);
//关闭连接
s.close();
}
}