Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of SSL/TLS in Netty, MINA and Twisted

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the Netty, MINA, Twisted SSL/TLS example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

1. Related terms

Before learning the SSL/TLS protocol, you should first understand some related concepts:

Symmetric encryption: both encryption and decryption use the same key. The commonly used algorithms are DES, 3DES and AES, which are simpler and faster than asymmetric encryption algorithms.

Asymmetric encryption: unlike symmetric encryption algorithms, asymmetric encryption algorithms have two keys: a public key (which can be public) and a private key (private). For example, if the client uses public key encryption, then even if others have a public key, they cannot be decrypted, and can only be decrypted through the server's private key. RSA algorithm is a typical asymmetric encryption algorithm.

Digital certificate: a digital certificate is a string of data that contains a public key and is issued by an authoritative organization. many digital certificates need to be purchased or free, and they can also be generated by themselves. in this paper, we will use self-signed method to generate digital certificates.

2. SSL/TLS process

Before the server and client using the SSL/TLS protocol begin to communicate, there is a handshake phase:

1) the client sends a request: in this step, the client generates a random number and sends it to the server.

2) Server response: in this step, the server will return to the client a server digital certificate (the certificate contains the public key for encryption), and the server will also generate a random number to the client.

3) client response: in this step, the client will first verify the validity of the digital certificate, and then generate a random number, which will be encrypted using the public key in step 2 using an asymmetric encryption algorithm (such as RSA algorithm) and transmitted to the server. The ciphertext can only be decrypted through the server's private key.

4) the server finally responded: the handshake is over.

After the handshake, both the client and the server have three random numbers for the handshake phase above. Both the client and the server randomly generate a key through these three, and then all the communication content is encrypted and transmitted by the symmetric encryption algorithm, and the server and the client begin to communicate securely.

3. Generate private keys and certificates

Use openssl to generate private keys and certificates:

Openssl req-x509-newkey rsa:2048-nodes-days 365-keyout private.pem-out cert.crt

After running the above command, a private key file (private.pem) and a certificate file (cert.crt) are generated in the current directory.

The generated private key and certificate Twisted and Netty can be used directly, but the requirement of MINA for the format of private key file is to convert the private key of text file into the private key of binary file in order to convert pem format into der format. Openssl converts private.pem to private.der private key file:

Openssl pkcs8-topk8-inform PEM-in private.pem-outform DER-nocrypt-out private.der

4. SSL/TLS server

Next, on the basis of Netty, MINA and Twisted learning a series of 02:TCP message boundary problems and dividing messages by lines, the SSL/TLS layer is added.

1) MINA

MINA can implement SSL/TLS through SslFilter, and the code to initialize SslFilter is cumbersome:

Public class MinaServer {

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

String certPath = "/ Users/wucao/Desktop/ssl/cert.crt"; / / Certificate

String privateKeyPath = "/ Users/wucao/Desktop/ssl/private.der"; / / Private key

/ / Certificate

/ / https://docs.oracle.com/javase/7/docs/api/java/security/cert/X509Certificate.html

InputStream inStream = null

Certificate certificate = null

Try {

InStream = new FileInputStream (certPath)

CertificateFactory cf = CertificateFactory.getInstance ("X.509")

Certificate = cf.generateCertificate (inStream)

} finally {

If (inStream! = null) {

InStream.close ()

}

}

/ / Private key

PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec (Files.readAllBytes (new File (privateKeyPath). ToPath ()

PrivateKey privateKey = KeyFactory.getInstance ("RSA") .generatePrivate (keySpec)

KeyStore ks = KeyStore.getInstance (KeyStore.getDefaultType ())

Ks.load (null, null)

Certificate [] certificates = {certificate}

Ks.setKeyEntry ("key", privateKey, ".toCharArray (), certificates)

KeyManagerFactory kmf = KeyManagerFactory.getInstance (KeyManagerFactory.getDefaultAlgorithm ())

Kmf.init (ks, ".toCharArray ())

SSLContext sslContext = SSLContext.getInstance ("TLS")

SslContext.init (kmf.getKeyManagers (), null, null)

IoAcceptor acceptor = new NioSocketAcceptor ()

DefaultIoFilterChainBuilder chain = acceptor.getFilterChain ()

Chain.addLast ("ssl", new SslFilter (sslContext)); / / SslFilter needs to be put first

Chain.addLast ("codec", new ProtocolCodecFilter (new TextLineCodecFactory (Charset.forName ("UTF-8"), "\ r\ n", "\ r\ n")

Acceptor.setHandler (new TcpServerHandle ())

Acceptor.bind (new InetSocketAddress (8080))

}

}

Class TcpServerHandle extends IoHandlerAdapter {

@ Override

Public void exceptionCaught (IoSession session, Throwable cause)

Throws Exception {

Cause.printStackTrace ()

}

@ Override

Public void messageReceived (IoSession session, Object message)

Throws Exception {

String line = (String) message

System.out.println ("messageReceived:" + line)

}

@ Override

Public void sessionCreated (IoSession session) throws Exception {

System.out.println ("sessionCreated")

}

@ Override

Public void sessionClosed (IoSession session) throws Exception {

System.out.println ("sessionClosed")

}

}

2) Netty

Netty implements SSL/TLS by adding a SslHandler, which is relatively concise compared to MINA:

Public class NettyServer {

Public static void main (String [] args) throws InterruptedException, SSLException {

File certificate = new File ("/ Users/wucao/Desktop/ssl/cert.crt"); / / Certificate

File privateKey = new File ("/ Users/wucao/Desktop/ssl/private.pem"); / / Private key

Final SslContext sslContext = SslContextBuilder.forServer (certificate, privateKey). Build ()

EventLoopGroup bossGroup = new NioEventLoopGroup ()

EventLoopGroup workerGroup = new NioEventLoopGroup ()

Try {

ServerBootstrap b = new ServerBootstrap ()

B.group (bossGroup, workerGroup)

.channel (NioServerSocketChannel.class)

.childHandler (new ChannelInitializer () {

@ Override

Public void initChannel (SocketChannel ch)

Throws Exception {

ChannelPipeline pipeline = ch.pipeline ()

/ / SslHandler should be put at the front.

SslHandler sslHandler = sslContext.newHandler (ch.alloc ())

Pipeline.addLast (sslHandler)

Pipeline.addLast (new LineBasedFrameDecoder (80))

Pipeline.addLast (new StringDecoder (CharsetUtil.UTF_8))

Pipeline.addLast (new TcpServerHandler ())

}

});

ChannelFuture f = b.bind (8080) .sync ()

F.channel (). CloseFuture (). Sync ()

} finally {

WorkerGroup.shutdownGracefully ()

BossGroup.shutdownGracefully ()

}

}

}

Class TcpServerHandler extends ChannelInboundHandlerAdapter {

@ Override

Public void channelRead (ChannelHandlerContext ctx, Object msg) {

String line = (String) msg

System.out.println ("channelRead:" + line)

}

@ Override

Public void channelActive (ChannelHandlerContext ctx) {

System.out.println ("channelActive")

}

@ Override

Public void channelInactive (ChannelHandlerContext ctx) {

System.out.println ("channelInactive")

}

@ Override

Public void exceptionCaught (ChannelHandlerContext ctx, Throwable cause) {

Cause.printStackTrace ()

Ctx.close ()

}

}

3) Twisted

It is also very simple for Twisted to implement SSL/TLS, just replace reactor.listenTCP with reactor.listenSSL.

#-*-coding:utf-8-*-

From twisted.protocols.basic import LineOnlyReceiver

From twisted.internet.protocol import Factory

From twisted.internet import reactor, ssl

SslContext = ssl.DefaultOpenSSLContextFactory (

'/ Users/wucao/Desktop/ssl/private.pem', # Private key

'/ Users/wucao/Desktop/ssl/cert.crt', # Public key

)

Class TcpServerHandle (LineOnlyReceiver):

Def connectionMade (self):

Print 'connectionMade'

Def connectionLost (self, reason):

Print 'connectionLost'

Def lineReceived (self, data):

Print 'lineReceived:' + data

Factory = Factory ()

Factory.protocol = TcpServerHandle

Reactor.listenSSL (8080, factory, sslContext)

Reactor.run ()

5. SSL/TLS client

Here we still use Java to write a SSL/TLS client to test the above three server programs. It should be noted that in the above introduction of the SSL/TLS process, the server will pass the certificate to the client in step 2 of the SSL/TLS handshake phase, and the client will verify the validity of the certificate in step 3, so the following code will first make the client trust the certificate generated by openssl in order to correctly complete the SSL/TLS handshake.

Public class SSLClient {

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

/ / the client trust changes the certificate, which will be used to verify the validity of the certificate sent by the server

String certPath = "/ Users/wucao/Desktop/ssl/cert.crt"

InputStream inStream = null

Certificate certificate = null

Try {

InStream = new FileInputStream (certPath)

CertificateFactory cf = CertificateFactory.getInstance ("X.509")

Certificate = cf.generateCertificate (inStream)

} finally {

If (inStream! = null) {

InStream.close ()

}

}

KeyStore ks = KeyStore.getInstance (KeyStore.getDefaultType ())

Ks.load (null, null)

Ks.setCertificateEntry ("cert", certificate)

TrustManagerFactory tmf = TrustManagerFactory.getInstance ("sunx509")

Tmf.init (ks)

SSLContext sslContext = SSLContext.getInstance ("TLS")

SslContext.init (null, tmf.getTrustManagers (), null)

SSLSocketFactory socketFactory = sslContext.getSocketFactory ()

Socket socket = null

OutputStream out = null

Try {

Socket = socketFactory.createSocket ("localhost", 8080)

Out = socket.getOutputStream ()

/ / request server

String lines = "there is a bright moonlight in front of the bed\ r\ n suspected frost on the ground\ r\ nlooking up at the bright moon in the sky\ r\ nlooking down and missing your hometown\ r\ n"

Byte [] outputBytes = lines.getBytes ("UTF-8")

Out.write (outputBytes)

Out.flush ()

} finally {

/ / close the connection

Out.close ()

Socket.close ()

}

}

} Thank you for reading this article carefully. I hope the article "sample Analysis of SSL/TLS in Netty, MINA and Twisted" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report