Apache Mina - SSL配置

[url=http://zjumty.iteye.com/blog/1884465]Apache MINA文档系列[/url]

[size=x-large]Apache Mina - SSL配置[/size]

本文中我们看一下如何为一个简单的客户端/服务器应用程序配置安全套接字(SSL)。 我们需要一下3个步骤:

创建SSLContext
服务器部分
客户端部分

[size=medium]第一步 – 创建SSLContext[/size]

SSLContext是用来创建SSLSocket或SSLEngine的。在下面的例子中有一个类SSLContextGenerator用来创建SSLContext。要进行加密的传输,我们还需要两个密钥文件:keystore和truststore。要创建这两个文件可以参见“[url=http://zjumty.iteye.com/blog/1885356]用keytool创建Keystore和Trustsotre文件[/url]”。在SSLContextGenerator里我们使用了下面两个工厂类:

KeyStoreFactory - 创建和配置KeyStore实例的工厂类。
SSLContextFactory - 创建和配置SSLContext实例。


SSLContextGenerator.java

package com.sample.ssl;

import java.io.File;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import org.apache.mina.filter.ssl.KeyStoreFactory;
import org.apache.mina.filter.ssl.SslContextFactory;

public class SSLContextGenerator
{
public SSLContext getSslContext()
{
SSLContext sslContext = null;
try
{
File keyStoreFile = new File("/home/giftsam/Desktop/certificates/keystore");
File trustStoreFile = new File("/home/giftsam/Desktop/certificates/truststore");

if (keyStoreFile.exists() && trustStoreFile.exists()) {
final KeyStoreFactory keyStoreFactory = new KeyStoreFactory();
System.out.println("Url is: " + keyStoreFile.getAbsolutePath());
keyStoreFactory.setDataFile(keyStoreFile);
keyStoreFactory.setPassword("techbrainwave");

final KeyStoreFactory trustStoreFactory = new KeyStoreFactory();
trustStoreFactory.setDataFile(trustStoreFile);
trustStoreFactory.setPassword("techbrainwave");

final SslContextFactory sslContextFactory = new SslContextFactory();
final KeyStore keyStore = keyStoreFactory.newInstance();
sslContextFactory.setKeyManagerFactoryKeyStore(keyStore);

final KeyStore trustStore = trustStoreFactory.newInstance();
sslContextFactory.setTrustManagerFactoryKeyStore(trustStore);
sslContextFactory.setKeyManagerFactoryKeyStorePassword("techbrainwave");
sslContext = sslContextFactory.newInstance();
System.out.println("SSL provider is: " + sslContext.getProvider());
} else {
System.out.println("Keystore or Truststore file does not exist");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return sslContext;
}
}


[size=medium]第二步 - 服务器部分[/size]

服务器部分有两个类,SSLServer 和 SSLServerHandler。 SSLServer类里,我们用MINA的SSLFilter来加密和解密传输的数据。同时这个类会立即触发SSL的Handshake的处理(如果你不想立即触发handshake处理,可以指定构造函数的autostart参数为false)。

注意:SSLFilter只用在TCP/IP的连接。

IoAcceptor接口用来接受客户端过来的连接请求,触发IoHandler中的事件。在本例中使用了两个Filter,LoggingFilter用来记录所有的事件和请求。 第二个是ProtocolCodecFilter用来把进来的ByteBuffer转换成POJO的消息对象。SSLFilter要放在过滤器链的最前端,以保证后面的Filter里利用到的数据是已经解密过的。

SSLServer.java


package com.sample.ssl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class SSLServer
{
private static final int PORT = 5000;

private static void addSSLSupport(DefaultIoFilterChainBuilder chain)
{
try
{
SslFilter sslFilter = new SslFilter(new SSLContextGenerator().getSslContext());
chain.addLast("sslFilter", sslFilter);
System.out.println("SSL support is added..");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

public static void main(String[] args) throws IOException, GeneralSecurityException
{
IoAcceptor acceptor = new NioSocketAcceptor();
DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();

addSSLSupport(chain);

chain.addLast("logger", new LoggingFilter());
chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

acceptor.setHandler(new SSLServerHandler());
acceptor.getSessionConfig().setReadBufferSize(2048);
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
acceptor.bind(new InetSocketAddress(PORT));
System.out.println("Server Started..");
}
}


SSLServerHandler类有4个方法。sessionOpened在会话打开是被调用,可以在这个方法里进行会话的初始配置如会话空闲时间。messageReceived方法在接收到客户端发来的消息后被调用。会话闲置10秒后会调用sessionIdle方法,我们在这里把会话结束掉。当异常发生后messageReceived方法会被调用,我们在这个方法里关闭会话。

SSLServerHandler.java


package com.sample.ssl;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SSLServerHandler extends IoHandlerAdapter
{
private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
private int idleTimeout = 10;

@Override
public void sessionOpened(IoSession session)
{
// 设置会话闲置为10秒
session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, idleTimeout);
session.setAttribute("Values: ");
}

@Override
public void messageReceived(IoSession session, Object message)
{
System.out.println("Message received in the server..");
System.out.println("Message is: " + message.toString());
}

@Override
public void sessionIdle(IoSession session, IdleStatus status)
{
logger.info("Transaction is idle for " + idleTimeout + "secs, So disconnecting..");
// 把空闲的会话关闭
session.close();
}

@Override
public void exceptionCaught(IoSession session, Throwable cause)
{
// 出现异常是也关闭连接
session.close();
}
}


[size=medium]第三步 - 客户端部分[/size]

客户端部分有两个类SSLClient和SSLClientHandler。在SSLClient类里,我们同样适用SSLFilter来加密和解密传输的数据。 SSLFilter的UseClientMode属性被设置为True,标识这个SSLFilter在做handshake时是客户端模式。

IoConnector用来和服务器通信并且触发IoHandler中的事件。和服务器端一样,我们使用了LoggingFilter和ProtocolCodecFilter。 ConnectFuture用来实现异步的连接请求。


package com.sample.ssl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class SSLClient
{
private static final int REMORT_PORT = 5000;

public static void main(String[] args) throws IOException, InterruptedException, GeneralSecurityException
{
IoConnector connector = new NioSocketConnector();
connector.getSessionConfig().setReadBufferSize(2048);

SSLContext sslContext = new SSLContextGenerator().getSslContext();
System.out.println("SSLContext protocol is: " + sslContext.getProtocol());

SslFilter sslFilter = new SslFilter(sslContext);
sslFilter.setUseClientMode(true);
connector.getFilterChain().addFirst("sslFilter", sslFilter);

connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

connector.setHandler(new SSLClientHandler("Hello Server.."));
ConnectFuture future = connector.connect(new InetSocketAddress("172.108.0.6", REMORT_PORT));
future.awaitUninterruptibly();

if (!future.isConnected())
{
return;
}
IoSession session = future.getSession();
session.getConfig().setUseReadOperation(true);
session.getCloseFuture().awaitUninterruptibly();
System.out.println("After Writing");
connector.dispose();
}
}

IoHandler部分,和服务端一样有“sessionOpened”, “messageReceived” 和 “exceptionCaught”方法。

SSLClientHandler.java

package com.sample.ssl;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SSLClientHandler extends IoHandlerAdapter
{
private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
private final String values;
private boolean finished;

public SSLClientHandler(String values)
{
this.values = values;
}

public boolean isFinished()
{
return finished;
}

@Override
public void sessionOpened(IoSession session)
{
session.write(values);
}

@Override
public void messageReceived(IoSession session, Object message)
{
logger.info("Message received in the client..");
logger.info("Message is: " + message.toString());
}

@Override
public void exceptionCaught(IoSession session, Throwable cause)
{
session.close();
}
}


现在我们来测试一下上面的代码。 先执行SSLServer,然后执行SSLClient。就可以看到在控制台里可以输出了一下内容:

服务端输出


Url is: /home/giftsam/Desktop/certificates/keystore
SSL Provider is: SunJSSE version 1.6
SSL support is added..
Server Started..
Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
INFO: CREATED
Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
INFO: OPENED
Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
INFO: RECEIVED: HeapBuffer[pos=0 lim=15 cap=36: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 0A]
Message received in the server..
Message is: Hello Server..
Dec 10, 2010 8:38:09 PM org.apache.mina.filter.logging.LoggingFilter log
INFO: IDLE
Dec 10, 2010 8:38:09 PM com.sample.ssl.SSLServerHandler sessionIdle
INFO: Transaction is idle for 10secs, So disconnecting..
Dec 10, 2010 8:38:09 PM org.apache.mina.filter.logging.LoggingFilter log
INFO: CLOSED


客户端输出


Url is: /home/giftsam/Desktop/certificates/keystore
SSL Provider is: SunJSSE version 1.6
SSLContext protocol is: TLS
Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
INFO: CREATED
Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
INFO: OPENED
Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
INFO: SENT: HeapBuffer[pos=0 lim=15 cap=16: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 0A]
Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
INFO: SENT: HeapBuffer[pos=0 lim=0 cap=0: empty]


参考链接:http://www.techbrainwave.com/?p=973

你可能感兴趣的:(nio,mina,Java,network)