Using SSL with Netty

Netty Code

Following code explains how to connect to HTTPS using Netty Client. NettyClientInitializer is the bootstrap class which adds all handlers.

The best way to enable HTTPs is to add SSLContextHandler in the beginning of netty pipeline.

public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
SslContext sslCtx = SSLUtils.getSslContext();
pipeline.addLast(sslCtx.newHandler(ch.alloc()));
// Add handlers next
pipeline.addLast(new NettyClientHandler(clientCallBack));
pipeline.addLast(new IncomingMessageHandler(clientCallBack));
}
}
public class SSLUtils {
private static Logger logger = LoggerFactory.getLogger(SSLUtils.class);
private static final String cert_alias = "my_cert";
private static final String cert_path = System.getProperty("cert_path");
public static SslContext getSslContext() throws Exception {
KeyStore ks = createKeystore(readCertificate());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(ks, null);
TrustManagerFactory tmFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmFactory.init(ks);
final SslContext sslContext = SslContextBuilder.forClient()
.keyManager(kmf).trustManager(tmFactory).build();
return sslContext;
}
private static KeyStore createKeystore(java.security.cert.Certificate cert) {
KeyStore ks = null;
try {
ks = KeyStore.getInstance("JKS");
ks.load(null, null);
ks.setCertificateEntry(cert_alias, cert);
} catch (CertificateException | IOException | NoSuchAlgorithmException
| KeyStoreException e) {
logger.error("Error creating keystore " + cert_path, e);
throw new RuntimeException(e);
}
return ks;
}
private static java.security.cert.Certificate readCertificate() {
java.security.cert.Certificate cert = null;
try {
CertificateFactory certificateFactory = CertificateFactory
.getInstance("X.509");
FileInputStream certificateStream = new FileInputStream(cert_path);
cert = certificateFactory.generateCertificate(certificateStream);
certificateStream.close();
} catch (CertificateException | IOException e) {
logger.error("Error loading certificate " + cert_path, e);
throw new RuntimeException(e);
}
return cert;
}
}
view raw SSLUtils.java hosted with ❤ by GitHub