使用netty和ssl证书的简单方法?

时间:2015-11-24 16:39:12

标签: java ssl netty syslog

我正在尝试使用netty使用SSL写入系统日志服务器,我想我已经掌握了网络部分,我似乎只需要添加这一行:channel.pipeline().addLast("ssl", sslCtx.newHandler(channel.alloc(), host, 5000))。< / p>

完整代码:

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());
}

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

-----BEGIN CERTIFICATE-----
MIIDBjCCAe4CCQCmD....gM8vZVmYXULV8A==
-----END CERTIFICATE-----

我认为必须在java中跳过大量的箍才能做到这一点。肯定有一种更简单的方法来使用SSL和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();

1 个答案:

答案 0 :(得分:4)

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

SslContext sslCtx = SslContextBuilder.forServer(new File(certPath), new File(keyPath), null).build();

然后添加到管道:

pipeline.addLast(sslCtx.newHandler(channel .alloc()));