使用带有SSL证书的Netty的简单方法?

Iai*_*inS 0 java ssl syslog netty

我正在尝试使用netty通过SSL写入syslog服务器,我想我已经开始关注netty部分了,我似乎只需要添加以下行: channel.pipeline().addLast("ssl", sslCtx.newHandler(channel.alloc(), host, 5000))

完整代码:

bootstrap.channel(NioSocketChannel.class)
    .option(ChannelOption.SO_KEEPALIVE, true)
    .handler(new TcpSyslogEventEncoder());

try {
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, 5000));
  channel = future.syncUninterruptibly().channel();
  channel.pipeline().addLast("ssl", sslCtx.newHandler(channel.alloc(), host, 5000));
}
catch (Exception e) {
  System.out.println("Unable to connect to host.  Cause is " + e.toString());
}
Run Code Online (Sandbox Code Playgroud)

我的问题是获取SslContext(sslCtx)对象设置。我已经有了要使用的证书(这是一个.crt文件,其中包含以下文本:

-----BEGIN CERTIFICATE-----
MIIDBjCCAe4CCQCmD....gM8vZVmYXULV8A==
-----END CERTIFICATE-----
Run Code Online (Sandbox Code Playgroud)

我看到必须跳过Java中的铁环负载才能做到这一点。肯定有一种更简单的方法可以将netty与SSL一起使用吗?我设置sslCtx的代码是:

EventLoopGroup group = null;
Bootstrap bootstrap = null;
Channel channel = null;
boolean initialized = false;
boolean connected = false;
java.io.FileInputStream fis = null;


// find out if keystore already exists
KeyStore ks = null;
try {
  ks = KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e) {
  e.printStackTrace();
}
// get user password and file input stream
char[] password = {'p','a','s','s','w','o','r','d'};


try {
  fis = new java.io.FileInputStream("newKeyStoreNamep12");
  ks.load(fis, password);
} catch (CertificateException e) {
  e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
  e.printStackTrace();
} finally {
  if (fis != null) {
    fis.close();
  }
}


FileInputStream certFile = new FileInputStream("server.crt");
BufferedInputStream bis = new BufferedInputStream(certFile);

CertificateFactory cf = null;
try {
  cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
  e.printStackTrace();
}

Certificate cert = null;


while (bis.available() > 0) {
  try {
    cert = cf.generateCertificate(bis);
  } catch (CertificateException e) {
    e.printStackTrace();
  }
  System.out.println("cert is: " + cert.toString());
}

ks.setCertificateEntry("myalias", cert);


KeyManagerFactory kmf;
kmf = KeyManagerFactory.getInstance("IbmX509");
kmf.init(ks, password);



group = new NioEventLoopGroup();
bootstrap = new Bootstrap();
bootstrap.group(group);
initialized = true;
connected = false;


SslContextBuilder ctxBuilder =     SslContextBuilder.forClient().keyManager(kmf);
SslContext sslCtx = ctxBuilder.build();
Run Code Online (Sandbox Code Playgroud)

Suv*_*ica 5

不知道使用什么版本,但是在4.0.30中,您可以像这样设置ssl上下文:

SslContext sslCtx = SslContextBuilder.forServer(new File(certPath), new File(keyPath), null).build();
Run Code Online (Sandbox Code Playgroud)

然后添加到管道中:

pipeline.addLast(sslCtx.newHandler(channel .alloc()));
Run Code Online (Sandbox Code Playgroud)