开启SSL
开启SSL非常简单,getty已经提供了易用且健壮的SSL实现。服务端与客户端唯一的区别就是 setClientMode(),服务器端需设置为false。
AioServerStarter server = new AioServerStarter(8888);
server.channelInitializer(new ChannelInitializer() {
@Override
public void initChannel(AioChannel channel) throws Exception {
DefaultChannelPipeline defaultChannelPipeline = channel.getDefaultChannelPipeline();
//获取证书
String pkPath = ResourceUtils.getURL("classpath:serverStore.jks")
.getPath();
//ssl配置
SslConfig sSLConfig = new SslConfig();
sSLConfig.setKeyFile(pkPath);
sSLConfig.setKeyPassword("123456");
sSLConfig.setKeystorePassword("123456");
sSLConfig.setTrustFile(pkPath);
sSLConfig.setTrustPassword("123456");
//设置服务器模式
sSLConfig.setClientMode(false);
//设置单向验证或双向验证
sSLConfig.setClientAuth(ClientAuth.NONE);
//初始化ssl服务,默认protocolVersion="TLSv1.2",可通过构造方法指定
SslService sSLService = new SslService(sSLConfig);
//把ssl插件注入责任链即可,需要添加到责任链的第一位
defaultChannelPipeline.addFirst(new SslHandler(channel,sSLService));
defaultChannelPipeline.addLast(new DelimiterFrameDecoder(DelimiterFrameDecoder.lineDelimiter));
defaultChannelPipeline.addLast(new StringDecoder());
defaultChannelPipeline.addLast(new SimpleHandler());
}
});
server.start();
SslConfig 参数| 参数名 | 数据类型 | 备注 || ———————— | ———— | —————————————————————————————————————— || clientMode | boolean | 配置引擎在握手时使用客户端(或服务器)模式 || keyFile | String | keystore路径 || keystorePassword | String | keystore密码 || keyPassword | String | 管理密钥,需要key的密码,通常是keystore密码,这个密码也可以为null || trustFile | String | 签名证书路径,通常签名证书直接使用jks,也就是上面的keystore文件,并非cer文件 || trustPassword | String | 签名证书密码 |
ClientAuth
参数 | 类型 | 备注 |
---|---|---|
NONE | boolean | 单向验证 |
REQUIRE | boolean | 双向向验证 |
客户端示例
AioClientStarter client = new AioClientStarter(aioConfig);
client.channelInitializer(new ChannelInitializer() {
@Override
public void initChannel(AioChannel channel) throws Exception {
//责任链
DefaultChannelPipeline defaultChannelPipeline = channel.getDefaultChannelPipeline();
//当服务器端配置为单向认证时,客户端只需开启ssl。可以不配置证书,双向认证则客户端需要配置证书
SslConfig sSLConfig = new SslConfig();
//别忘了设置为客户端模式
sSLConfig.setClientMode(true);
SslService sSLService = new SslService(sSLConfig);
defaultChannelPipeline.addFirst(new SslHandler(channel,sSLService));
//指定结束符解码器
defaultChannelPipeline.addLast(new DelimiterFrameDecoder(DelimiterFrameDecoder.lineDelimiter));
//字符串解码器
defaultChannelPipeline.addLast(new StringDecoder());
//定义消息解码器
defaultChannelPipeline.addLast(new SimpleHandler());
}
});
try {
client.start();
} catch (Exception e) {
e.printStackTrace();
}