下面列出了javax.net.ssl.SSLContext#createSSLEngine ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public SSLSocketChannel(final SSLContext sslContext, final String hostname, final int port, final InetAddress localAddress, final boolean client) throws IOException {
this.socketAddress = new InetSocketAddress(hostname, port);
this.channel = SocketChannel.open();
if (localAddress != null) {
final SocketAddress localSocketAddress = new InetSocketAddress(localAddress, 0);
this.channel.bind(localSocketAddress);
}
this.hostname = hostname;
this.port = port;
this.engine = sslContext.createSSLEngine();
this.engine.setUseClientMode(client);
engine.setNeedClientAuth(true);
streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
/**
* Constructor for a secure ChannelIO variant.
*/
public SslReadWriteSelectorHandler(SocketChannel sc, SelectionKey selectionKey,
SSLContext sslContext) throws IOException {
super(sc);
sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(false);
initialHSStatus = HandshakeStatus.NEED_UNWRAP;
initialHSComplete = false;
int netBBSize = sslEngine.getSession().getPacketBufferSize();
inNetBB = ByteBuffer.allocate(netBBSize);
outNetBB = ByteBuffer.allocate(netBBSize);
outNetBB.position(0);
outNetBB.limit(0);
int appBBSize = sslEngine.getSession().getApplicationBufferSize();
requestBB = ByteBuffer.allocate(appBBSize);
while (!doHandshake(selectionKey)) {
}
}
/**
* @param channelPipeline channelPipeline
* @param serverBean 服务配置参数
*/
protected void initHandler(ChannelPipeline channelPipeline, InitNetty serverBean){
if (serverBean.isSsl()){
if (!ObjectUtils.allNotNull(serverBean.getJksCertificatePassword(),serverBean.getJksFile(),serverBean.getJksStorePassword())){
throw new NullPointerException(UndefinedInChatConstant.SSL_NOT_FIND);
}
try {
SSLContext context = SslUtil.createSSLContext("JKS",serverBean.getJksFile(),serverBean.getJksStorePassword());
SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(false);
engine.setNeedClientAuth(false);
channelPipeline.addLast(BootstrapConstant.SSL,new SslHandler(engine));
System.out.println("open ssl success");
} catch (Exception e) {
e.printStackTrace();
}
}
intProtocolHandler(channelPipeline,serverBean);
channelPipeline.addLast(new IdleStateHandler(serverBean.getHeart(),0,0));
channelPipeline.addLast(new DefaultAbstractHandler(new AbstractHandlerService(ConfigManager.inChatVerifyService, ConfigManager.asyncListener)));
}
/**
* 初始化SSL
*/
private void initSSL(ChannelPipeline pipeline, SslConfig ssl) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
InputStream ksInputStream = HttpChannelInitializer.class.getResourceAsStream(ssl.getJksPath());
ks.load(ksInputStream, ssl.getJksPwd().toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks,ssl.getJksPwd().toCharArray());
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(kmf.getKeyManagers(), null, null);
SSLEngine engine = sslCtx.createSSLEngine();
engine.setUseClientMode(false);
engine.setNeedClientAuth(false);
pipeline.addLast("ssl",new SslHandler(engine));
}
@Override
void initChannelImpl(final SocketChannel channel) {
/* Add SSL handler first if SSL context is provided */
final SSLContext sslContext = certManagerSrv.getServerContext();
if (sslContext != null) {
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false); // work in a server mode
engine.setNeedClientAuth(true); // need client authentication
if (protocols != null && protocols.length > 0) {
//Set supported protocols
engine.setEnabledProtocols(protocols);
LOG.debug("Supported ssl protocols {}",
Arrays.toString(engine.getSupportedProtocols()));
LOG.debug("Enabled ssl protocols {}",
Arrays.toString(engine.getEnabledProtocols()));
}
if (cipherSuites != null && cipherSuites.length > 0) {
//Set supported cipher suites
engine.setEnabledCipherSuites(cipherSuites);
LOG.debug("Enabled cipher suites {}",
Arrays.toString(engine.getEnabledCipherSuites()));
}
channel.pipeline().addLast("ssl", new SslHandler(engine));
}
super.initChannelImpl(channel);
}
public SSLSocketChannel(final SSLContext sslContext, final String hostname, final int port, final InetAddress localAddress, final boolean client) throws IOException {
this.socketAddress = new InetSocketAddress(hostname, port);
this.channel = SocketChannel.open();
if (localAddress != null) {
final SocketAddress localSocketAddress = new InetSocketAddress(localAddress, 0);
this.channel.bind(localSocketAddress);
}
this.hostname = hostname;
this.port = port;
this.engine = sslContext.createSSLEngine();
this.engine.setUseClientMode(client);
engine.setNeedClientAuth(true);
streamInManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
streamOutManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getPacketBufferSize()));
appDataManager = new BufferStateManager(ByteBuffer.allocate(engine.getSession().getApplicationBufferSize()));
}
/**
* Returns client ssl engine.
*
* @param context - SSLContext to get SSLEngine from.
* @param useSNI - flag used to enable or disable using SNI extension.
* Needed for Kerberos.
*/
public static SSLEngine getClientSSLEngine(
SSLContext context, boolean useSNI) {
SSLEngine clientEngine = context.createSSLEngine(HOST, 80);
clientEngine.setUseClientMode(true);
if (useSNI) {
SNIHostName serverName = new SNIHostName(SERVER_NAME);
List<SNIServerName> serverNames = new ArrayList<>();
serverNames.add(serverName);
SSLParameters params = clientEngine.getSSLParameters();
params.setServerNames(serverNames);
clientEngine.setSSLParameters(params);
}
return clientEngine;
}
public static SSLEngine createSSLEngine(SSLOption option, SSLCustom custom) {
SSLContext context = createSSLContext(option, custom);
SSLEngine engine =
context.createSSLEngine();
engine.setEnabledProtocols(option.getProtocols().split(","));
String[] supported = engine.getSupportedCipherSuites();
String[] eanbled = option.getCiphers().split(",");
engine.setEnabledCipherSuites(getEnabledCiphers(supported, eanbled));
engine.setNeedClientAuth(option.isAuthPeer());
return engine;
}
private SSLEngine createInsecureSSLEngine() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, INSECURE_TRUST_MANAGER, new SecureRandom());
SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(true);
return engine;
}
SSLStreams(ServerImpl server, SSLContext sslctx, SocketChannel chan) throws IOException {
this.server = server;
this.time = server;
this.sslctx = sslctx;
this.chan = chan;
InetSocketAddress addr = (InetSocketAddress)chan.socket().getRemoteSocketAddress();
this.engine = sslctx.createSSLEngine(addr.getHostName(), addr.getPort());
this.engine.setUseClientMode(false);
HttpsConfigurator cfg = server.getHttpsConfigurator();
this.configureEngine(cfg, addr);
this.wrapper = new SSLStreams.EngineWrapper(chan, this.engine);
}
private SSLEngine createInsecureSSLEngine() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, INSECURE_TRUST_MANAGER, new SecureRandom());
SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(true);
return engine;
}
SSLStreams(ServerImpl server, SSLContext sslctx, SocketChannel chan) throws IOException {
this.server = server;
this.time = server;
this.sslctx = sslctx;
this.chan = chan;
InetSocketAddress addr = (InetSocketAddress)chan.socket().getRemoteSocketAddress();
this.engine = sslctx.createSSLEngine(addr.getHostName(), addr.getPort());
this.engine.setUseClientMode(false);
HttpsConfigurator cfg = server.getHttpsConfigurator();
this.configureEngine(cfg, addr);
this.wrapper = new SSLStreams.EngineWrapper(chan, this.engine);
}
private static SslHandler createSslHandler(){
try {
SSLContext sslContext = createSSLContext("JKS", ClassUtil.getClassLoader().getResource("wss.jks").getPath(), "netty123");
//SSLEngine 此类允许使用ssl安全套接层协议进行安全通信
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
return new SslHandler(engine);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
SSLStreams(ServerImpl server, SSLContext sslctx, SocketChannel chan) throws IOException {
this.server = server;
this.time = server;
this.sslctx = sslctx;
this.chan = chan;
InetSocketAddress addr = (InetSocketAddress)chan.socket().getRemoteSocketAddress();
this.engine = sslctx.createSSLEngine(addr.getHostName(), addr.getPort());
this.engine.setUseClientMode(false);
HttpsConfigurator cfg = server.getHttpsConfigurator();
this.configureEngine(cfg, addr);
this.wrapper = new SSLStreams.EngineWrapper(chan, this.engine);
}
public static void main (String[] args) throws Exception {
SSLContext context = SSLContext.getDefault();
// set the property before initialization SSLEngine.
System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");
SSLEngine cliEngine = context.createSSLEngine();
cliEngine.setUseClientMode(true);
SSLEngine srvEngine = context.createSSLEngine();
srvEngine.setUseClientMode(false);
SSLSession cliSession = cliEngine.getSession();
SSLSession srvSession = srvEngine.getSession();
// check packet buffer sizes.
if (cliSession.getPacketBufferSize() < 33049 ||
srvSession.getPacketBufferSize() < 33049) {
throw new Exception("Don't accept large SSL/TLS fragments");
}
// check application data buffer sizes.
if (cliSession.getApplicationBufferSize() < 32768 ||
srvSession.getApplicationBufferSize() < 32768) {
throw new Exception(
"Don't accept large SSL/TLS application data ");
}
}
/**
* Returns a new {@link SSLEngine} constructed from the config settings.
*
* @return a {@link SSLEngine} ready to be used.
*/
public SSLEngine get() {
try {
String pass = env.sslKeystorePassword();
char[] password = pass == null || pass.isEmpty() ? null : pass.toCharArray();
KeyStore ks = env.sslKeystore();
if (ks == null) {
String ksFile = env.sslKeystoreFile();
if (ksFile != null && !ksFile.isEmpty()) {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream(ksFile), password);
}
}
KeyStore ts = env.sslTruststore();
if (ts == null) {
String tsFile = env.sslTruststoreFile();
if (tsFile != null && !tsFile.isEmpty()) {
// filepath found, open and init
String tsPassword = env.sslTruststorePassword();
char[] tspass = tsPassword == null || tsPassword.isEmpty() ? null : tsPassword.toCharArray();
ts = KeyStore.getInstance(KeyStore.getDefaultType());
ts.load(new FileInputStream(tsFile), tspass);
}
}
if (ks == null && ts == null) {
throw new IllegalStateException("Either a KeyStore or a TrustStore " +
"need to be provided (or both).");
} else if (ks == null) {
ks = ts;
LOGGER.debug("No KeyStore provided, using provided TrustStore to initialize both factories.");
} else if (ts == null) {
ts = ks;
LOGGER.debug("No TrustStore provided, using provided KeyStore to initialize both factories.");
}
String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
kmf.init(ks, password);
tmf.init(ts);
if (!sslContextProtocol.startsWith("TLS")) {
throw new IllegalArgumentException(
"SSLContext Protocol does not start with TLS, this is to prevent "
+ "insecure protocols (Like SSL*) to be used. Potential candidates "
+ "are TLS (default), TLSv1, TLSv1.1, TLSv1.2, TLSv1.3 depending on "
+ "the Java version used.");
}
SSLContext ctx = SSLContext.getInstance(sslContextProtocol);
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLEngine engine = ctx.createSSLEngine(hostname, port);
engine.setUseClientMode(true);
if (env.sslHostnameVerificationEnabled()) {
SSLParameters sslParameters = engine.getSSLParameters();
sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
engine.setSSLParameters(sslParameters);
}
return engine;
} catch (Exception ex) {
throw new SSLException("Could not create SSLEngine.", ex);
}
}
private static SSLEngine defaultSSLEngineFactory(SSLContext sslContext) {
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(true);
return engine;
}
public static AsyncTcpSocketSsl wrapServerSocket(AsyncTcpSocket asyncTcpSocket,
SSLContext sslContext, Executor executor) {
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(false);
return create(asyncTcpSocket, sslEngine, executor);
}
private SSLEngine makeSSLEngine(SSLContext context, boolean client, boolean clientAuthRequired) {
SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(client);
engine.setNeedClientAuth(clientAuthRequired);
return engine;
}
private ChannelHandler createSslHandler(SSLContext sslContext) {
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(true);
return new SslHandler(sslEngine);
}