您的位置:首页 > 理论基础 > 计算机网络

Https 代理 sslsocket

2016-02-27 23:57 645 查看

1. 什么是SSLSocket

JDK文档指出,SSLSocket扩展Socket并提供使用SSL或TLS协议的安全套接字。

这种套接字是正常的流套接字,但是它们在基础网络传输协议(如TCP)上添加了安全保护层。

具体安全方面的讨论见下一篇。本篇重点关注SSLSocket及相关几个类的使用。

2. SSLSocket和相关类

SSLSocket来自jsse(Java Secure Socket Extension)。



(1)SSLContext: 此类的实例表示安全套接字协议的实现, 它是SSLSocketFactory、SSLServerSocketFactory和SSLEngine的工厂。

(2)SSLSocket: 扩展自Socket

(3)SSLServerSocket: 扩展自ServerSocket

(4)SSLSocketFactory: 抽象类,扩展自SocketFactory, SSLSocket的工厂

(5)SSLServerSocketFactory: 抽象类,扩展自ServerSocketFactory, SSLServerSocket的工厂

(6)KeyStore: 表示密钥和证书的存储设施

(7)KeyManager: 接口,JSSE密钥管理器

(8)TrustManager: 接口,信任管理器(?翻译得很拗口)

(9)X590TrustedManager: TrustManager的子接口,管理X509证书,验证远程安全套接字

3. SSLContext的使用

[java] view plain copy print?

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

X509TrustManager x509m = new X509TrustManager() {

@Override

public X509Certificate[] getAcceptedIssuers() {

return null;

}

@Override

public void checkServerTrusted(X509Certificate[] chain,

String authType) throws CertificateException {

}

@Override

public void checkClientTrusted(X509Certificate[] chain,

String authType) throws CertificateException {

}

};

// 获取一个SSLContext实例

SSLContext s = SSLContext.getInstance("SSL");

// 初始化SSLContext实例

s.init(null, new TrustManager[] { x509m },

new java.security.SecureRandom());

// 打印这个SSLContext实例使用的协议

System.out.println("缺省安全套接字使用的协议: " + s.getProtocol());

// 获取SSLContext实例相关的SSLEngine

SSLEngine e = s.createSSLEngine();

System.out

.println("支持的协议: " + Arrays.asList(e.getSupportedProtocols()));

System.out.println("启用的协议: " + Arrays.asList(e.getEnabledProtocols()));

System.out.println("支持的加密套件: "

+ Arrays.asList(e.getSupportedCipherSuites()));

System.out.println("启用的加密套件: "

+ Arrays.asList(e.getEnabledCipherSuites()));

}

运行结果如下:



SSLContext.getProtocol(): 返回当前SSLContext对象的协议名称

SSLContext.init(): 初始化当前SSLContext对象。 三个参数均可以为null。 详见JDK文档。

SSLEngine.getSupportedProtocols()等几个方法可以返回些 Engine上支持/已启用的协议、支持/已启用的加密套件


4. SSLSocket和SSLServerSocket的使用

这两个类的用法跟Socket/ServerSocket的用法比较类似。看下面的例子(主要为了验证SSLSocket的用法 ,I/O和多线程处理比较随意)


4.1 SSLServerSocket

(1)新建一个SSLServerSocket,并开始监听来自客户端的连接

[java] view plain copy print?

// 抛出异常

// javax.net.ssl.SSLException: No available certificate or key corresponds

// to the SSL cipher suites which are enabled.

public static void notOk() throws IOException {

SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory

.getDefault();

SSLServerSocket server = (SSLServerSocket) factory

.createServerSocket(10000);

System.out.println("ok");

server.accept();

}

server.accept()处抛出异常, 提示缺少证书。与ServerSocket不同, SSLServerSocket需要证书来进行安全验证。

使用keytool工具生成一个证书。 步骤如下, 得到一个名为cmkey的证书文件



(2)重新完善上面的代码。 主要增加两个功能: 使用名为cmkey的证书初始化SSLContext,
echo客户端的消息。 代码如下

[java] view plain copy print?

// 启动一个ssl server socket

// 配置了证书, 所以不会抛出异常

public static void sslSocketServer() throws Exception {

// key store相关信息

String keyName = "cmkey";

char[] keyStorePwd = "123456".toCharArray();

char[] keyPwd = "123456".toCharArray();

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

// 装载当前目录下的key store. 可用jdk中的keytool工具生成keystore

InputStream in = null;

keyStore.load(in = Test2.class.getClassLoader().getResourceAsStream(

keyName), keyPwd);

in.close();

// 初始化key manager factory

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory

.getDefaultAlgorithm());

kmf.init(keyStore, keyPwd);

// 初始化ssl context

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

context.init(kmf.getKeyManagers(),

new TrustManager[] { new MyX509TrustManager() },

new SecureRandom());

// 监听和接收客户端连接

SSLServerSocketFactory factory = context.getServerSocketFactory();

SSLServerSocket server = (SSLServerSocket) factory

.createServerSocket(10002);

System.out.println("ok");

Socket client = server.accept();

System.out.println(client.getRemoteSocketAddress());

// 向客户端发送接收到的字节序列

OutputStream output = client.getOutputStream();

// 当一个普通 socket 连接上来, 这里会抛出异常

// Exception in thread "main" javax.net.ssl.SSLException: Unrecognized

// SSL message, plaintext connection?

InputStream input = client.getInputStream();

byte[] buf = new byte[1024];

int len = input.read(buf);

System.out.println("received: " + new String(buf, 0, len));

output.write(buf, 0, len);

output.flush();

output.close();

input.close();

// 关闭socket连接

client.close();

server.close();

}


4.2 SSLSocket

(1)我们先使用一个普通的Socket尝试连接服务器端

[java] view plain copy print?

// 通过socket连接服务器

public static void socket() throws UnknownHostException, IOException {

Socket s = new Socket("localhost", 10002);

System.out.println(s);

System.out.println("ok");

OutputStream output = s.getOutputStream();

InputStream input = s.getInputStream();

output.write("alert".getBytes());

System.out.println("sent: alert");

output.flush();

byte[] buf = new byte[1024];

int len = input.read(buf);

System.out.println("received:" + new String(buf, 0, len));

}

结果客户端和服务器端都出错。 客户端的错误是接收到乱码。



服务器则抛出异常

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

(2)改成SSLSocket, 但是不使用证书。客户端抛出
sun.security.provider.certpath.SunCertPathBuilderException: unable to
find valid certification path to requested target

[java] view plain copy print?

// 不使用证书, 通过ssl socket连接服务器

// 抛出异常, 提示找不到证书

public static void sslSocket() throws UnknownHostException, IOException {

SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory

.getDefault();

SSLSocket s = (SSLSocket) factory.createSocket("localhost", 10002);

System.out.println("ok");

OutputStream output = s.getOutputStream();

InputStream input = s.getInputStream();

output.write("alert".getBytes());

System.out.println("sent: alert");

output.flush();

byte[] buf = new byte[1024];

int len = input.read(buf);

System.out.println("received:" + new String(buf, 0, len));

}

程序客户在不持有证书的情况下直接进行连接,服务器端会产生运行时异常javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown,不允许进行连接。 我们可以指定像下面这样执行客户端,服务器端可以成功echo客户端的发出的字符串"alert"

java -Djavax.net.ssl.trustStore=cmkey Client

这里的cmkey即前面生成的证书文件。

(3)改成SSLSocket, 对SSLContext进行如下初始化。

[java] view plain copy print?

public static void sslSocket2() throws Exception {

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

// 初始化

context.init(null,

new TrustManager[] { new Test2.MyX509TrustManager() },

new SecureRandom());

SSLSocketFactory factory = context.getSocketFactory();

SSLSocket s = (SSLSocket) factory.createSocket("localhost", 10002);

System.out.println("ok");

OutputStream output = s.getOutputStream();

InputStream input = s.getInputStream();

output.write("alert".getBytes());

System.out.println("sent: alert");

output.flush();

byte[] buf = new byte[1024];

int len = input.read(buf);

System.out.println("received:" + new String(buf, 0, len));

}

转载出处:http://410063005.iteye.com/blog/1751243点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: