netty配置SSL、netty配置https(开发)
我们在开发下使用ssl,所用的证书将不被客户端信任。
方案一
快速。使用netty提供的临时签发证书
private static SslContext sslContext = null;public ServerChannelHandler(RouterConfig config) {this.config = config;try {if (sslContext != null)return;// 使用临时签发的一个证书SelfSignedCertificate ssc = new SelfSignedCertificate();sslContext = SslContextBuilder.forServer(ssc.certificate(),ssc.privateKey()).build();} catch (Exception e) {e.printStackTrace();}}
配置
@Slf4j
public class ServerChannelHandler extends ChannelInitializer<SocketChannel> {private final RouterConfig config;private static SslContext sslContext = null;public ServerChannelHandler(RouterConfig config) {this.config = config;try {if (sslContext != null)return;// 使用临时签发的一个证书SelfSignedCertificate ssc = new SelfSignedCertificate();sslContext = SslContextBuilder.forServer(ssc.certificate(),ssc.privateKey()).build();} catch (Exception e) {e.printStackTrace();}}@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();// 使用netty临时签发的证书pipeline.addLast(sslContext.newHandler(ch.alloc()));pipeline.addLast(new HttpServerCodec());// http编解码pipeline.addLast(new HttpObjectAggregator(config.getMaxContentLength()));pipeline.addLast(new DispatcherHandler(config));}
}
访问时需要你提前加上https,不会为你自动重定向到https
https://localhost:9595/
但是此时你发现控制台:
这是因为证书不被客户端信任,如果你是使用 logback
日志,可以配置忽略它:
logback.xml
的configuration
中添加
<logger name="io.netty.channel.DefaultChannelPipeline" level="OFF"/>
上面的警告日志将不再打印,nice~
方案二
使用jdk自签一个jks
证书:
keytool -genkeypair -alias lk -keyalg RSA -keypass 123456 -storepass 123456 -keyalg RSA -keysize 2048 -validity 3650 -keystore lk.jks
配置ssl
@Slf4j
public class ServerChannelHandler extends ChannelInitializer<SocketChannel> {private final RouterConfig config;public ServerChannelHandler(RouterConfig config) {this.config = config;}@Overrideprotected void initChannel(SocketChannel ch) throws Exception {ChannelPipeline pipeline = ch.pipeline();// ssl, 每次访问都要加载新的 SSLEngine 对象SSLEngine sslEngine = getSslContext().createSSLEngine();// 声明服务端sslEngine.setUseClientMode(false);pipeline.addLast(new SslHandler(sslEngine));pipeline.addLast(new HttpServerCodec());// http编解码pipeline.addLast(new HttpObjectAggregator(config.getMaxContentLength()));pipeline.addLast(new DispatcherHandler(config));}private static SSLContext getSslContext() throws Exception {// 密码char[] passArray = "123456".toCharArray();SSLContext sslContext = SSLContext.getInstance("TLSv1");KeyStore ks = KeyStore.getInstance("JKS");//加载keytool 生成的文件FileInputStream inputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\temp\\ssl\\lk.jks");ks.load(inputStream, passArray);KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());kmf.init(ks, passArray);sslContext.init(kmf.getKeyManagers(), null, null);inputStream.close();return sslContext;}
}
效果