`
小斌张
  • 浏览: 89496 次
  • 性别: Icon_minigender_1
  • 来自: 河北
社区版块
存档分类
最新评论

apache mina ssl配置

    博客分类:
  • mina
阅读更多
文章转自: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.
分享到:
评论

相关推荐

    apache-mina-2.0.4.rar_apache mina_mina

    - **mina-filter**模块:包含了各种预定义的过滤器,例如日志记录、压缩、SSL加密等。 - **mina-integration-spring**模块:如果你的项目使用Spring框架,这个模块可以帮助你更好地集成Mina。 通过分析源码,你可以...

    mina sslfilter大用法

    通过以上步骤,你已经了解了如何在Apache Mina中使用`SslFilter`来实现SSL/TLS通信。这个例子是一个很好的起点,可以帮助初学者理解如何在Mina框架中集成安全功能。如果有任何问题或需要进一步的帮助,可以联系...

    Apache Mina帮助文档

    Apache Mina支持多种网络协议,如TCP、UDP、SSL/TLS以及自定义协议。此外,它还提供了对常见应用层协议如HTTP、FTP、SMTP的支持,方便开发者快速构建网络服务。 **5. 高度可扩展性和灵活性** Mina的架构设计使得它...

    一个Apache MINA使用案例源代码ApacheMina

    Apache MINA是一个高性能、异步事件驱动的网络应用程序框架,主要设计用于简化开发服务器端的高性能网络应用。这个框架提供了一种抽象层,允许开发者使用相同的API处理多种不同的传输协议,如TCP/IP、UDP/IP以及SSL/...

    基于 MINA 的 TLS/SSL NIO Socket 实现(二)

    在本篇博文中,我们将深入探讨如何利用Apache MINA库实现基于TLS/SSL的NIO(非阻塞I/O)Socket通信。MINA是一个高度可扩展的网络应用框架,广泛用于构建高性能、高并发的网络应用程序,如服务器端的TCP和UDP服务。...

    Apache Mina Server 2.0 抢鲜体验

    Apache Mina Server 2.0 是一款高性能、可扩展的网络通信框架,广泛应用于开发网络应用服务器,如TCP/IP和UDP服务。这个框架允许开发者用Java编写高效的网络应用程序,简化了网络编程的复杂性。Mina 2.0 版本在前一...

    Apache Mina2服务器和客户端简单实例

    Apache Mina2是一个高度可扩展且高性能的网络通信框架,主要设计用于简化开发网络应用,如TCP/IP和UDP协议的服务端和客户端。它提供了一种事件驱动、非阻塞I/O模型,使得开发者能够更专注于业务逻辑,而不是底层的...

    Apache-Mina-2.rar_apache mina_java mina_mina_mina-core-1.1.3

    Apache Mina的名称来源于"Multi-purpose Infrastructure for Network Applications",它提供了一套事件驱动、非阻塞I/O的API,支持多种传输协议,如TCP/IP、UDP/IP和SSL/TLS等。这使得Mina可以用于创建高性能的...

    Apache mina源代码框架解析

    这只是Mina功能的冰山一角,实际应用中,Mina支持更复杂的网络服务,包括SSL/TLS加密、心跳检测、多协议支持等。对于深入学习Mina,你可以进一步探索其内部的事件驱动模型、异步I/O机制,以及如何自定义过滤器和...

    Apache MINA 2.0 用户指南中英文对照阅读版[带书签]

    本资源包含两个 pdf 文档,一本根据官方最新文档 (http://mina.apache.org/mina-project/userguide/user-guide-toc.html) 整理的 mina_2.0_user_guide_en.pdf,一个中文翻译的 mina_2.0_user_guide_cn.pdf。...

    apache_mina_maven 客户端测试程序

    5. **Maven 配置**:在 `pom.xml` 文件中,会声明 Apache MINA 作为依赖,并定义构建过程。这包括编译、测试、打包等阶段。 6. **测试用例**:在 `g_net_client_test` 文件中,可能包含了单元测试或集成测试,用于...

    apache mina 简单示例

    Apache Mina是一个开源框架,主要用于构建高性能、高可用性的网络应用程序。它提供了异步事件驱动的网络应用编程接口(API),适用于TCP/IP和UDP/IP协议,如Socket和SSL/TLS。Mina的目标是简化网络编程,使开发者...

    apache-mina-2.1.3-bin.tar.zip

    Apache MINA是一个高性能、异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。这个“apache-mina-2.1.3-bin.tar.zip”文件包含了Apache MINA的最新版本2.1.3,适用于Java开发者,便于...

    apache-mina-2.0.4-src

    2. **协议无关性**:Mina支持多种网络协议,如TCP、UDP、SSL/TLS、HTTP、FTP等,开发者可以通过简单的配置就能实现不同协议的服务。 3. **丰富的过滤器链**:Mina使用过滤器架构,允许在数据传输过程中插入各种处理...

    apache-mina-2.0.16

    Apache MINA(Multipurpose Infrastructure for Network Applications)是一个高性能、异步事件驱动的网络应用程序框架,主要用于简化开发服务器端和客户端的网络应用。标题"apache-mina-2.0.16"表明我们讨论的是...

    apache-mina-2.0.7架包与源码

    3. **多协议支持**:MINA提供了一种统一的API,可以方便地处理多种网络协议,如TCP/IP、UDP/IP、SSL/TLS等。 4. **过滤器链**:MINA的过滤器机制允许开发者通过定义和串联一系列处理单元(过滤器)来构建复杂的网络...

    Apache Mina入门(完成版)

    Mina支持多种协议,如TCP/IP、UDP/IP以及SSL/TLS等,广泛应用于Java平台上服务器端的开发。 在“Apache Mina入门(完成版)”这份资料中,你将了解到以下关键知识点: 1. **Mina架构**:Mina的核心设计理念是事件...

    Apache_MINA_2_用户指南.pdf

    Apache MINA 2 用户指南 Apache MINA 2 是一个基于 Java 语言的网络应用框架,旨在帮助开发者快速构建高性能、可靠、可扩展的网络应用程序。该框架提供了一个灵活的架构,使得开发者可以轻松地构建各种类型的网络...

    Apache MINA基于JAVA的网络服务器框架 教程.zip

    5. **丰富的API**:MINA提供了丰富的API,包括Socket和Datagram API,以及用于处理SSL/TLS安全通信的API。 6. **易于扩展**:MINA的设计使得添加新协议或扩展现有功能变得简单。 教程中的文件可能包含以下内容: ...

    apache-mina-2.0.7-src.zip

    5. **构建脚本**:如Ant或Maven配置文件,用于编译、打包和测试MINA项目。 6. **许可证文件**:包含了Apache软件基金会的开源许可证,明确MINA的使用、分发和修改的条款。 通过研究这个源代码,开发者可以学习到...

Global site tag (gtag.js) - Google Analytics