apache mina ssl配置
文章转自:Apache Mina – SSL Configuration
MINA SSL 设置:
Introduction
Quite some time back, I had wrote an article to create a simple client/server application using Apache Mina 2.0.x. In that article the transaction between the client and server is unsecured. In order to make a secured transaction between the client and the server, SSL should be configured. In this article, Let us see how to configure Secured Socket Layer(SSL) for a sample Client/Server application using 3 easy steps,
1.Generate SSLContext
2.Server part
3.Client part
Step 1 – Generate SSLContext
SSLContext is a factory for secure socket or SSLEngine. For the sample application, A class named “SSLGenerator” is used to generate the SSLContext. To make a secured transaction, Two types of key files are needed they are “Keystore” and “Truststore” file. The Creation of these two files has been explained in the article “Step by step tutorial to create Keystore and Truststore file “. The factory classes used in the SSLContextGenerator class is,
KeyStoreFactory - This factory class is used to create and configures a new Keystore instance.
SSLContextFactory - This factory class is used to create and configures a new SSLContext.
SSLContextGenerator.java
view sourceprint?
01 package com.sample.ssl;
02
03 import java.io.File;
04 import java.security.KeyStore;
05 import javax.net.ssl.SSLContext;
06 import org.apache.mina.filter.ssl.KeyStoreFactory;
07 import org.apache.mina.filter.ssl.SslContextFactory;
08
09 /**
10 * @author giftsam
11 */
12 public class SSLContextGenerator
13 {
14 public SSLContext getSslContext()
15 {
16 SSLContext sslContext = null;
17 try
18 {
19 File keyStoreFile = new File("/home/giftsam/Desktop/certificates/keystore");
20 File trustStoreFile = new File("/home/giftsam/Desktop/certificates/truststore");
21
22 if (keyStoreFile.exists() && trustStoreFile.exists())
23 {
24 final KeyStoreFactory keyStoreFactory = new KeyStoreFactory();
25 System.out.println("Url is: " + keyStoreFile.getAbsolutePath());
26 keyStoreFactory.setDataFile(keyStoreFile);
27 keyStoreFactory.setPassword("techbrainwave");
28
29 final KeyStoreFactory trustStoreFactory = new KeyStoreFactory();
30 trustStoreFactory.setDataFile(trustStoreFile);
31 trustStoreFactory.setPassword("techbrainwave");
32
33 final SslContextFactory sslContextFactory = new SslContextFactory();
34 final KeyStore keyStore = keyStoreFactory.newInstance();
35 sslContextFactory.setKeyManagerFactoryKeyStore(keyStore);
36
37 final KeyStore trustStore = trustStoreFactory.newInstance();
38 sslContextFactory.setTrustManagerFactoryKeyStore(trustStore);
39 sslContextFactory.setKeyManagerFactoryKeyStorePassword("techbrainwave");
40 sslContext = sslContextFactory.newInstance();
41 System.out.println("SSL provider is: " + sslContext.getProvider());
42 }
43 else
44 {
45 System.out.println("Keystore or Truststore file does not exist");
46 }
47 }
48 catch (Exception ex)
49 {
50 ex.printStackTrace();
51 }
52 return sslContext;
53 }
54 }
Step 2 – Server part
For the server part two classes named “SSLServer” and “SSLServerHandler” has been used. In the SSLServer class, “SSLFilter” class is used to encrypt and decrypt the data exchanged in the session, Also it triggers the SSLHandshake procedure immediately(If you don’t want the handshake procedure to start immediately, please specify false as autostart parameter in the constructor).
Note: SSLFilter works only for the TCP/IP connections.
An interface named “IoAcceptor” is used to accept the incoming connections from the client and that fires the event to the handler. Two filters has been used, the first one is the “LoggingFilter” which logs all the events and requests and the second one is the “ProtocolCodecFilter” which is used to convert an incoming ByteBuffer into message POJO.
SSLServer.java
view sourceprint?01 package com.sample.ssl;
02
03 import java.io.IOException;
04 import java.net.InetSocketAddress;
05 import java.nio.charset.Charset;
06 import java.security.GeneralSecurityException;
07 import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
08
09 import org.apache.mina.core.session.IdleStatus;
10 import org.apache.mina.core.service.IoAcceptor;
11 import org.apache.mina.filter.codec.ProtocolCodecFilter;
12 import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
13 import org.apache.mina.filter.logging.LoggingFilter;
14 import org.apache.mina.filter.ssl.SslFilter;
15 import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
16
17 /**
18 * @author giftsam
19 */
20 public class SSLServer
21 {
22 private static final int PORT = 5000;
23
24 private static void addSSLSupport(DefaultIoFilterChainBuilder chain)
25 {
26 try
27 {
28 SslFilter sslFilter = new SslFilter(new SSLContextGenerator().getSslContext());
29 chain.addLast("sslFilter", sslFilter);
30 System.out.println("SSL support is added..");
31 }
32 catch (Exception ex)
33 {
34 ex.printStackTrace();
35 }
36 }
37
38 public static void main(String[] args) throws IOException, GeneralSecurityException
39 {
40 IoAcceptor acceptor = new NioSocketAcceptor();
41 DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
42
43 addSSLSupport(chain);
44
45 chain.addLast("logger", new LoggingFilter());
46 chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
47
48 acceptor.setHandler(new SSLServerHandler());
49 acceptor.getSessionConfig().setReadBufferSize(2048);
50 acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
51 acceptor.bind(new InetSocketAddress(PORT));
52 System.out.println("Server Started..");
53 }
54 }
The SSLServerHandler class contains four methods. The first method “sessionOpened” is called when the session is opened and it is used to set the session idle time. The second method “receiveMessage” is used to receive the message sent by the client. The other two methods “sessionIdle” is used to close the session when it was idle for 10 secs and the fourth method “exceptionCaught” is used to close the session when an exception occured.
SSLServerHandler.java
package com.sample.ssl;
02
03 import org.apache.mina.core.session.IdleStatus;
04 import org.apache.mina.core.service.IoHandlerAdapter;
05 import org.apache.mina.core.session.IoSession;
06 import org.slf4j.Logger;
07 import org.slf4j.LoggerFactory;
08
09 /**
10 * @author giftsam
11 */
12 public class SSLServerHandler extends IoHandlerAdapter
13 {
14 private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
15 private int idleTimeout = 10;
16
17 @Override
18 public void sessionOpened(IoSession session)
19 {
20 // set idle time to 10 seconds
21 session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, idleTimeout);
22
23 session.setAttribute("Values: ");
24 }
25
26 @Override
27 public void messageReceived(IoSession session, Object message)
28 {
29 System.out.println("Message received in the server..");
30 System.out.println("Message is: " + message.toString());
31 }
32
33 @Override
34 public void sessionIdle(IoSession session, IdleStatus status)
35 {
36 logger.info("Transaction is idle for " + idleTimeout + "secs, So disconnecting..");
37 // disconnect an idle client
38 session.close();
39 }
40
41 @Override
42 public void exceptionCaught(IoSession session, Throwable cause)
43 {
44 // close the connection on exceptional situation
45 session.close();
46 }
47 }
Step 3 – Client part
For the client part two classes named “SSLClient” and “SSLClientHandler” has been used. In the “MinaClient” class the SSLFilter class is used to encrypt and decrypt the data exchanged in the session and SSLFilter property UseClientMode should be set as true and that configures the socket to use client mode in its first handshake.
“IoConnector” interface is used to communicate with the server and that fires the event to the handler. Like the server part, The same “LoggingFilter” and “ProtocolCodecFilter” has been used. An interface named “ConnectFuture” is used to windup the asynchronous connection requests.
SSLClient.java
view sourceprint?
01 package com.sample.ssl;
02
03 import java.io.IOException;
04 import java.net.InetSocketAddress;
05 import java.nio.charset.Charset;
06 import java.security.GeneralSecurityException;
07 import javax.net.ssl.SSLContext;
08 import org.apache.mina.core.future.ConnectFuture;
09 import org.apache.mina.core.service.IoConnector;
10 import org.apache.mina.core.session.IoSession;
11 import org.apache.mina.filter.codec.ProtocolCodecFilter;
12 import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
13 import org.apache.mina.filter.logging.LoggingFilter;
14 import org.apache.mina.filter.ssl.SslFilter;
15 import org.apache.mina.transport.socket.nio.NioSocketConnector;
16
17 /**
18 * @author giftsam
19 */
20 public class SSLClient
21 {
22 private static final int REMORT_PORT = 5000;
23
24 public static void main(String[] args) throws IOException, InterruptedException, GeneralSecurityException
25 {
26 IoConnector connector = new NioSocketConnector();
27 connector.getSessionConfig().setReadBufferSize(2048);
28
29 SSLContext sslContext = new SSLContextGenerator().getSslContext();
30 System.out.println("SSLContext protocol is: " + sslContext.getProtocol());
31
32 SslFilter sslFilter = new SslFilter(sslContext);
33 sslFilter.setUseClientMode(true);
34 connector.getFilterChain().addFirst("sslFilter", sslFilter);
35
36 connector.getFilterChain().addLast("logger", new LoggingFilter());
37 connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
38
39 connector.setHandler(new SSLClientHandler("Hello Server.."));
40 ConnectFuture future = connector.connect(new InetSocketAddress("172.108.0.6", REMORT_PORT));
41 future.awaitUninterruptibly();
42
43 if (!future.isConnected())
44 {
45 return;
46 }
47 IoSession session = future.getSession();
48 session.getConfig().setUseReadOperation(true);
49 session.getCloseFuture().awaitUninterruptibly();
50 System.out.println("After Writing");
51 connector.dispose();
52 }
53 }
For the handler, Like the server part the same methods “sessionOpened”, “messageReceived” and “exceptionCaught” has been used.
SSLClientHandler.java
view sourceprint?
01 package com.sample.ssl;
02
03 import org.apache.mina.core.service.IoHandlerAdapter;
04 import org.apache.mina.core.session.IoSession;
05 import org.slf4j.Logger;
06 import org.slf4j.LoggerFactory;
07
08 /**
09 * @author giftsam
10 */
11 public class SSLClientHandler extends IoHandlerAdapter
12 {
13 private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
14 private final String values;
15 private boolean finished;
16
17 public SSLClientHandler(String values)
18 {
19 this.values = values;
20 }
21
22 public boolean isFinished()
23 {
24 return finished;
25 }
26
27 @Override
28 public void sessionOpened(IoSession session)
29 {
30 session.write(values);
31 }
32
33 @Override
34 public void messageReceived(IoSession session, Object message)
35 {
36 logger.info("Message received in the client..");
37 logger.info("Message is: " + message.toString());
38 }
39
40 @Override
41 public void exceptionCaught(IoSession session, Throwable cause)
42 {
43 session.close();
44 }
45 }
Now its time to test the preceding codes, First the code “SSLServer” should be executed and then execute the “SSLClient”, the outcome of the codes will looks like the below,
Output – Server
view sourceprint?
01 Url is: /home/giftsam/Desktop/certificates/keystore
02 SSL Provider is: SunJSSE version 1.6
03 SSL support is added..
04 Server Started..
05 Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
06 INFO: CREATED
07 Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
08 INFO: OPENED
09 Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
10 INFO: RECEIVED: HeapBuffer[pos=0 lim=15 cap=36: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 0A]
11 Message received in the server..
12 Message is: Hello Server..
13 Dec 10, 2010 8:38:09 PM org.apache.mina.filter.logging.LoggingFilter log
14 INFO: IDLE
15 Dec 10, 2010 8:38:09 PM com.sample.ssl.SSLServerHandler sessionIdle
16 INFO: Transaction is idle for 10secs, So disconnecting..
17 Dec 10, 2010 8:38:09 PM org.apache.mina.filter.logging.LoggingFilter log
18 INFO: CLOSED
Output – client
view sourceprint?
01 Url is: /home/giftsam/Desktop/certificates/keystore
02 SSL Provider is: SunJSSE version 1.6
03 SSLContext protocol is: TLS
04 Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
05 INFO: CREATED
06 Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
07 INFO: OPENED
08 Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
09 INFO: SENT: HeapBuffer[pos=0 lim=15 cap=16: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 0A]
10 Dec 10, 2010 8:37:59 PM org.apache.mina.filter.logging.LoggingFilter log
11 INFO: SENT: HeapBuffer[pos=0 lim=0 cap=0: empty]
Thats all folks. I hope this article clearly explains the steps to implement SSL for a client/server application using Apache Mina 2.0.x. If you find this article is useful for you, dont forget to leave your valuable comments. Have a joyous code day.