Java Examples for javax.net.ssl.SSLEngine
The following java examples will help you to understand the usage of javax.net.ssl.SSLEngine. These source code samples are taken from different open source projects.
Example 1
Project: android-sdk-sources-for-api-level-23-master File: SSLEngineTest.java View source code |
/** * Test for <code>SSLEngine(String host, int port)</code> constructor */ public void test_ConstructorLjava_lang_StringI01() throws Exception { int port = 1010; SSLEngine e = getEngine(null, port); assertNull(e.getPeerHost()); assertEquals(e.getPeerPort(), port); try { e.beginHandshake(); fail("should throw IllegalStateException"); } catch (IllegalStateException expected) { } e = getEngine(null, port); e.setUseClientMode(true); e.beginHandshake(); e = getEngine(null, port); e.setUseClientMode(false); e.beginHandshake(); }
Example 2
Project: ARTPart-master File: PSKKeyManagerProxy.java View source code |
@Override public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); boolean sslEngineVariant = (parameterTypes.length > 0) && (SSLEngine.class.equals(parameterTypes[parameterTypes.length - 1])); if ("getKey".equals(methodName)) { if (sslEngineVariant) { return getKey((String) args[0], (String) args[1], (SSLEngine) args[2]); } else { return getKey((String) args[0], (String) args[1], (Socket) args[2]); } } else if ("chooseServerKeyIdentityHint".equals(methodName)) { if (sslEngineVariant) { return chooseServerKeyIdentityHint((SSLEngine) args[0]); } else { return chooseServerKeyIdentityHint((Socket) args[0]); } } else if ("chooseClientKeyIdentity".equals(methodName)) { if (sslEngineVariant) { return chooseClientKeyIdentity((String) args[0], (SSLEngine) args[1]); } else { return chooseClientKeyIdentity((String) args[0], (Socket) args[1]); } } else { throw new IllegalArgumentException("Unexpected method: " + method); } }
Example 3
Project: android_libcore-master File: SSLEngineTest.java View source code |
/** * Test for <code>SSLEngine(String host, int port)</code> constructor * @throws NoSuchAlgorithmException */ @TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "Verification with incorrect parameters missed", method = "SSLEngine", args = { java.lang.String.class, int.class }) public void test_ConstructorLjava_lang_StringI01() throws NoSuchAlgorithmException { int port = 1010; SSLEngine e = getEngine(null, port); assertNull(e.getPeerHost()); assertEquals(e.getPeerPort(), port); try { e.beginHandshake(); } catch (IllegalStateException ex) { } catch (SSLException ex) { fail("unexpected SSLException was thrown."); } e = getEngine(null, port); e.setUseClientMode(true); try { e.beginHandshake(); } catch (SSLException ex) { } e = getEngine(null, port); e.setUseClientMode(false); try { e.beginHandshake(); } catch (SSLException ex) { } }
Example 4
Project: android-libcore64-master File: SSLEngineTest.java View source code |
/** * Test for <code>SSLEngine(String host, int port)</code> constructor * @throws NoSuchAlgorithmException */ public void test_ConstructorLjava_lang_StringI01() throws NoSuchAlgorithmException { int port = 1010; SSLEngine e = getEngine(null, port); assertNull(e.getPeerHost()); assertEquals(e.getPeerPort(), port); try { e.beginHandshake(); } catch (IllegalStateException ex) { } catch (SSLException ex) { fail("unexpected SSLException was thrown."); } e = getEngine(null, port); e.setUseClientMode(true); try { e.beginHandshake(); } catch (SSLException ex) { } e = getEngine(null, port); e.setUseClientMode(false); try { e.beginHandshake(); } catch (SSLException ex) { } }
Example 5
Project: android_platform_libcore-master File: SSLEngineTest.java View source code |
/** * Test for <code>SSLEngine(String host, int port)</code> constructor * @throws NoSuchAlgorithmException */ public void test_ConstructorLjava_lang_StringI01() throws NoSuchAlgorithmException { int port = 1010; SSLEngine e = getEngine(null, port); assertNull(e.getPeerHost()); assertEquals(e.getPeerPort(), port); try { e.beginHandshake(); } catch (IllegalStateException ex) { } catch (SSLException ex) { fail("unexpected SSLException was thrown."); } e = getEngine(null, port); e.setUseClientMode(true); try { e.beginHandshake(); } catch (SSLException ex) { } e = getEngine(null, port); e.setUseClientMode(false); try { e.beginHandshake(); } catch (SSLException ex) { } }
Example 6
Project: robovm-master File: SSLEngineTest.java View source code |
/** * Test for <code>SSLEngine(String host, int port)</code> constructor * @throws NoSuchAlgorithmException */ public void test_ConstructorLjava_lang_StringI01() throws NoSuchAlgorithmException { int port = 1010; SSLEngine e = getEngine(null, port); assertNull(e.getPeerHost()); assertEquals(e.getPeerPort(), port); try { e.beginHandshake(); } catch (IllegalStateException ex) { } catch (SSLException ex) { fail("unexpected SSLException was thrown."); } e = getEngine(null, port); e.setUseClientMode(true); try { e.beginHandshake(); } catch (SSLException ex) { } e = getEngine(null, port); e.setUseClientMode(false); try { e.beginHandshake(); } catch (SSLException ex) { } }
Example 7
Project: netty-in-action-master File: HttpsCodecInitializer.java View source code |
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
SSLEngine engine = context.newEngine(ch.alloc());
pipeline.addFirst("ssl", new SslHandler(engine));
if (client) {
pipeline.addLast("codec", new HttpClientCodec());
} else {
pipeline.addLast("codec", new HttpServerCodec());
}
}
Example 8
Project: Pitbull-master File: SSLChannelFactory.java View source code |
@Override
public ManagedChannel create(SocketChannel channel) throws Exception {
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
engine.setNeedClientAuth(false);
engine.setWantClientAuth(false);
SSLChannel sslChannel = new SSLChannel(channel, engine);
return new ManagedChannel(sslChannel, eventHandlerFactory.create());
}
Example 9
Project: bergamot-master File: TLSUtils.java View source code |
public static String[] computeSupportedProtocols(SSLEngine sslEngine, String[] wantedProtocols) {
Set<String> supported = new TreeSet<String>(Arrays.asList(sslEngine.getSupportedProtocols()));
// filter the wanted protocols with that is supported
List<String> protocols = new LinkedList<String>();
for (String wanted : wantedProtocols) {
if (supported.contains(wanted)) {
protocols.add(wanted);
}
}
return protocols.toArray(new String[0]);
}
Example 10
Project: BungeeCord-master File: HttpInitializer.java View source code |
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast("timeout", new ReadTimeoutHandler(HttpClient.TIMEOUT, TimeUnit.MILLISECONDS));
if (ssl) {
SSLEngine engine = SslContext.newClientContext().newEngine(ch.alloc(), host, port);
ch.pipeline().addLast("ssl", new SslHandler(engine));
}
ch.pipeline().addLast("http", new HttpClientCodec());
ch.pipeline().addLast("handler", new HttpHandler(callback));
}
Example 11
Project: FireFly-master File: TestNativeSSL.java View source code |
public static void main(String[] args) throws CertificateException, IOException {
// SslContext sslCtx = SslContext.newServerContext(SslProvider.OPENSSL);
SelfSignedCertificate ssc = new SelfSignedCertificate("www.fireflysource.com");
System.out.println(ssc.certificate().getAbsolutePath());
System.out.println(FileUtils.readFileToString(ssc.certificate(), "UTF-8"));
System.out.println();
System.out.println(ssc.privateKey().getAbsolutePath());
System.out.println(FileUtils.readFileToString(ssc.privateKey(), "UTF-8"));
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
System.out.println(SslContext.defaultServerProvider());
SSLEngine sslEngine = sslCtx.newEngine(PooledByteBufAllocator.DEFAULT);
sslCtx.newHandler(PooledByteBufAllocator.DEFAULT);
}
Example 12
Project: gearman-java-master File: GearmanServerInitializer.java View source code |
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (enableSSL) {
LOG.info("Enabling SSL");
SSLEngine engine = GearmanSslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("decoder", new Decoder());
pipeline.addLast("encoder", new Encoder());
pipeline.addLast("handler", new PacketHandler(networkManager));
}
Example 13
Project: javardices-master File: NettySslHttpServerInitializer.java View source code |
@Override
public void initChannel(SocketChannel ch) throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = ch.pipeline();
final SSLEngine sslEngine = ssl_context.createSSLEngine();
sslEngine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(sslEngine));
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("handler", handler);
}
Example 14
Project: netty-cookbook-master File: Http2OrHttpHandler.java View source code |
@Override
protected SelectedProtocol getProtocol(SSLEngine engine) {
String[] protocol = engine.getSession().getProtocol().split(":");
if (protocol != null && protocol.length > 1) {
SelectedProtocol selectedProtocol = SelectedProtocol.protocol(protocol[1]);
System.err.println("Selected Protocol is " + selectedProtocol);
return selectedProtocol;
}
return SelectedProtocol.UNKNOWN;
}
Example 15
Project: sitebricks-master File: MailClientPipelineFactory.java View source code |
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = Channels.pipeline();
if (config.getAuthType() != Auth.PLAIN) {
SSLEngine sslEngine = SSLContext.getDefault().createSSLEngine();
sslEngine.setUseClientMode(true);
SslHandler sslHandler = new SslHandler(sslEngine);
sslHandler.setEnableRenegotiation(true);
pipeline.addLast("ssl", sslHandler);
}
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
// and then business logic.
pipeline.addLast("handler", mailClientHandler);
return pipeline;
}
Example 16
Project: webpie-master File: SelfSignedSSLEngineFactory.java View source code |
@Override public SSLEngine createSslEngine(String host) { try { this.cachedHost = host; // Create/initialize the SSLContext with key material char[] passphrase = password.toCharArray(); // First initialize the key and trust material. KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(serverKeystore), passphrase); SSLContext sslContext = SSLContext.getInstance("TLS"); //****************Server side specific********************* // KeyManager's decide which key material to use. KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passphrase); sslContext.init(kmf.getKeyManagers(), null, null); //****************Server side specific********************* SSLEngine engine = sslContext.createSSLEngine(); engine.setUseClientMode(false); return engine; } catch (Exception e) { throw new RuntimeException(e); } }
Example 17
Project: errai-master File: SslHandlerFactory.java View source code |
/** * Initialize the {@link javax.net.ssl.SSLEngine} for the * {@link io.netty.handler.ssl.SslHandler}. Anytime the engine is null or no * more valid. Otherwise the previous created will be reused. * * @param keyPassword * @param keyStore * @return */ public static SSLEngine getSslEngine(final KeyStore keyStore, final String keyPassword) { if (sslEngine == null || sslEngine.isInboundDone() || sslEngine.isOutboundDone()) { try { final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keyStore, keyPassword.toCharArray()); final SSLContext sslc = SSLContext.getInstance("TLSv1"); sslc.init(kmf.getKeyManagers(), null, null); final SSLEngine sslEngine = sslc.createSSLEngine(); sslEngine.setUseClientMode(false); sslEngine.setNeedClientAuth(false); SslHandlerFactory.sslEngine = sslEngine; } catch (Exception e) { throw new RuntimeException("could not build SSL Engine", e); } } return sslEngine; }
Example 18
Project: aerogear-simplepush-server-master File: SockJSChannelInitializer.java View source code |
@Override
protected void initChannel(final SocketChannel socketChannel) throws Exception {
final ChannelPipeline pipeline = socketChannel.pipeline();
if (sockjsConfig.isTls()) {
final SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast(new SslHandler(engine));
}
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
final DefaultSimplePushServer simplePushServer = new DefaultSimplePushServer(datastore, simplePushConfig, privateKey);
pipeline.addLast(new NotificationHandler(simplePushServer));
pipeline.addLast(new CorsInboundHandler());
pipeline.addLast(new SockJsHandler(new SimplePushServiceFactory(sockjsConfig, simplePushServer)));
pipeline.addLast(backgroundGroup, new UserAgentReaperHandler(simplePushServer));
pipeline.addLast(new CorsOutboundHandler());
}
Example 19
Project: ambry-master File: SSLFactoryTest.java View source code |
@Test public void testSSLFactory() throws Exception { File trustStoreFile = File.createTempFile("truststore", ".jks"); SSLConfig sslConfig = new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.SERVER, trustStoreFile, "server")); SSLConfig clientSSLConfig = new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.CLIENT, trustStoreFile, "client")); SSLFactory sslFactory = new SSLFactory(sslConfig); SSLContext sslContext = sslFactory.getSSLContext(); SSLSocketFactory socketFactory = sslContext.getSocketFactory(); Assert.assertNotNull(socketFactory); SSLServerSocketFactory serverSocketFactory = sslContext.getServerSocketFactory(); Assert.assertNotNull(serverSocketFactory); SSLEngine serverSideSSLEngine = sslFactory.createSSLEngine("localhost", 9095, SSLFactory.Mode.SERVER); TestSSLUtils.verifySSLConfig(sslContext, serverSideSSLEngine, false); //client sslFactory = new SSLFactory(clientSSLConfig); sslContext = sslFactory.getSSLContext(); socketFactory = sslContext.getSocketFactory(); Assert.assertNotNull(socketFactory); serverSocketFactory = sslContext.getServerSocketFactory(); Assert.assertNotNull(serverSocketFactory); SSLEngine clientSideSSLEngine = sslFactory.createSSLEngine("localhost", 9095, SSLFactory.Mode.CLIENT); TestSSLUtils.verifySSLConfig(sslContext, clientSideSSLEngine, true); }
Example 20
Project: android-gradle-plugin-master File: SecureRandomGeneratorDetector.java View source code |
@Override
public void checkCall(@NonNull ClassContext context, @NonNull ClassNode classNode, @NonNull MethodNode method, @NonNull MethodInsnNode call) {
if (mIgnore) {
return;
}
String owner = call.owner;
String name = call.name;
if (name.equals(FOR_NAME)) {
if (call.getOpcode() != Opcodes.INVOKESTATIC || !owner.equals(JAVA_LANG_CLASS)) {
return;
}
AbstractInsnNode prev = LintUtils.getPrevInstruction(call);
if (prev instanceof LdcInsnNode) {
Object cst = ((LdcInsnNode) prev).cst;
//noinspection SpellCheckingInspection
if (cst instanceof String && "org.apache.harmony.xnet.provider.jsse.NativeCrypto".equals(cst)) {
mIgnore = true;
}
}
return;
}
// Look for calls that probably require a properly initialized random number generator.
assert owner.equals(JAVAX_CRYPTO_KEY_GENERATOR) || owner.equals(JAVA_SECURITY_KEY_PAIR_GENERATOR) || owner.equals(JAVAX_CRYPTO_KEY_AGREEMENT) || owner.equals(OWNER_SECURE_RANDOM) || owner.equals(JAVAX_CRYPTO_CIPHER) || owner.equals(JAVAX_CRYPTO_SIGNATURE) || owner.equals(JAVAX_NET_SSL_SSLENGINE) : owner;
boolean warn = false;
if (owner.equals(JAVAX_CRYPTO_SIGNATURE)) {
warn = name.equals(INIT_SIGN);
} else if (owner.equals(JAVAX_CRYPTO_CIPHER)) {
if (name.equals(INIT)) {
int arity = getDescArity(call.desc);
AbstractInsnNode node = call;
for (int i = 0; i < arity; i++) {
node = LintUtils.getPrevInstruction(node);
if (node == null) {
break;
}
}
if (node != null) {
int opcode = node.getOpcode();
if (// Cipher.WRAP_MODE
opcode == Opcodes.ICONST_3 || opcode == Opcodes.ICONST_1) {
// Cipher.ENCRYPT_MODE
warn = true;
}
}
}
} else if (name.equals(GET_INSTANCE) || name.equals(CONSTRUCTOR_NAME) || name.equals(WRAP) || name.equals(UNWRAP)) {
// For SSLEngine
warn = true;
}
if (warn) {
if (mLocation != null) {
return;
}
if (context.getMainProject().getMinSdk() > 18) {
// Fix no longer needed
mIgnore = true;
return;
}
if (context.getDriver().isSuppressed(ISSUE, classNode, method, call)) {
mIgnore = true;
} else {
mLocation = context.getLocation(call);
}
}
}
Example 21
Project: android-platform-tools-base-master File: SecureRandomGeneratorDetector.java View source code |
@Override
public void checkCall(@NonNull ClassContext context, @NonNull ClassNode classNode, @NonNull MethodNode method, @NonNull MethodInsnNode call) {
if (mIgnore) {
return;
}
String owner = call.owner;
String name = call.name;
if (name.equals(FOR_NAME)) {
if (call.getOpcode() != Opcodes.INVOKESTATIC || !owner.equals(JAVA_LANG_CLASS)) {
return;
}
AbstractInsnNode prev = LintUtils.getPrevInstruction(call);
if (prev instanceof LdcInsnNode) {
Object cst = ((LdcInsnNode) prev).cst;
//noinspection SpellCheckingInspection
if (cst instanceof String && "org.apache.harmony.xnet.provider.jsse.NativeCrypto".equals(cst)) {
mIgnore = true;
}
}
return;
}
// Look for calls that probably require a properly initialized random number generator.
assert owner.equals(JAVAX_CRYPTO_KEY_GENERATOR) || owner.equals(JAVA_SECURITY_KEY_PAIR_GENERATOR) || owner.equals(JAVAX_CRYPTO_KEY_AGREEMENT) || owner.equals(OWNER_SECURE_RANDOM) || owner.equals(JAVAX_CRYPTO_CIPHER) || owner.equals(JAVAX_CRYPTO_SIGNATURE) || owner.equals(JAVAX_NET_SSL_SSLENGINE) : owner;
boolean warn = false;
if (owner.equals(JAVAX_CRYPTO_SIGNATURE)) {
warn = name.equals(INIT_SIGN);
} else if (owner.equals(JAVAX_CRYPTO_CIPHER)) {
if (name.equals(INIT)) {
int arity = getDescArity(call.desc);
AbstractInsnNode node = call;
for (int i = 0; i < arity; i++) {
node = LintUtils.getPrevInstruction(node);
if (node == null) {
break;
}
}
if (node != null) {
int opcode = node.getOpcode();
if (// Cipher.WRAP_MODE
opcode == Opcodes.ICONST_3 || opcode == Opcodes.ICONST_1) {
// Cipher.ENCRYPT_MODE
warn = true;
}
}
}
} else if (name.equals(GET_INSTANCE) || name.equals(CONSTRUCTOR_NAME) || name.equals(WRAP) || name.equals(UNWRAP)) {
// For SSLEngine
warn = true;
}
if (warn) {
if (mLocation != null) {
return;
}
if (context.getMainProject().getMinSdk() > 18) {
// Fix no longer needed
mIgnore = true;
return;
}
if (context.getDriver().isSuppressed(ISSUE, classNode, method, call)) {
mIgnore = true;
} else {
mLocation = context.getLocation(call);
}
}
}
Example 22
Project: archived-net-virt-platform-master File: OVSDBClientPipelineFactory.java View source code |
@Override
public ChannelPipeline getPipeline() throws Exception {
JSONDecoder jsonRpcDecoder = new JSONDecoder();
JSONEncoder jsonRpcEncoder = new JSONEncoder();
ChannelPipeline pipeline = Channels.pipeline();
if (useSSL) {
// Add SSL handler first to encrypt and decrypt everything.
SSLEngine engine = BSNSslContextFactory.getClientContext().createSSLEngine();
engine.setUseClientMode(true);
// OVSDB supports *only* TLSv1
engine.setEnabledProtocols(new String[] { "TLSv1" });
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("jsondecoder", jsonRpcDecoder);
pipeline.addLast("jsonencoder", jsonRpcEncoder);
pipeline.addLast("jsonhandler", new JSONMsgHandler(currtsw, statusObject));
return pipeline;
}
Example 23
Project: channelmanager2-master File: SecProxyConnectOpCb.java View source code |
@Override
public void finished(Channel realChannel) throws IOException {
if (log.isLoggable(Level.FINE))
log.fine(realChannel + " Tcp connected, running handshake before fire connect");
SecTCPChannel secureChannel = channel;
SSLEngine sslEngine;
try {
if (svrChannel != null) {
sslEngine = sslFactory.createEngineForServerSocket();
secureChannel = new SecTCPChannel((TCPChannel) realChannel);
} else
sslEngine = sslFactory.createEngineForSocket();
} catch (GeneralSecurityException e) {
IOException ioe = new IOException(realChannel + "Security error");
ioe.initCause(e);
throw ioe;
}
SecSSLListener connectProxy = secureChannel.getConnectProxy();
AsyncSSLEngine handler = CREATOR.createSSLEngine(realChannel, sslEngine, null);
// AsynchSSLEngine handler = new AsynchSSLEngineImpl(realChannel, sslEngine);
// AsynchSSLEngine handler = new AsynchSSLEngineSynchronized(realChannel, sslEngine);
// AsynchSSLEngine handler = new AsynchSSLEngineQueued()
secureChannel.getReaderProxy().setHandler(handler);
handler.setListener(secureChannel.getConnectProxy());
connectProxy.setConnectCallback(new ProxyCallback(cb));
synchronized (secureChannel) {
if (log.isLoggable(Level.FINEST))
log.finest(realChannel + " about to register for reads");
if (!connectProxy.isClientRegistered()) {
if (log.isLoggable(Level.FINEST))
log.finest(realChannel + " register for reads");
realChannel.registerForReads(secureChannel.getReaderProxy());
}
}
handler.beginHandshake();
}
Example 24
Project: couchbase-jvm-core-master File: SSLEngineFactory.java View source code |
/** * 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) { ks = KeyStore.getInstance(KeyStore.getDefaultType()); String ksFile = env.sslKeystoreFile(); if (ksFile == null || ksFile.isEmpty()) { throw new IllegalArgumentException("Path to Keystore File must not be null or empty."); } ks.load(new FileInputStream(ksFile), password); } String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm); TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm); kmf.init(ks, password); tmf.init(ks); SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); SSLEngine engine = ctx.createSSLEngine(); engine.setUseClientMode(true); return engine; } catch (Exception ex) { throw new SSLException("Could not create SSLEngine.", ex); } }
Example 25
Project: dcache-master File: ClientGsiEngineDssContextFactory.java View source code |
@Override
public DssContext create(InetSocketAddress remoteSocketAddress, InetSocketAddress localSocketAddress) throws IOException {
try {
SSLEngine delegate = contextFactory.getContext(credential).createSSLEngine(remoteSocketAddress.getHostString(), remoteSocketAddress.getPort());
SSLParameters sslParameters = delegate.getSSLParameters();
String[] cipherSuites = toArray(filter(asList(sslParameters.getCipherSuites()), not(in(bannedCiphers))), String.class);
String[] protocols = toArray(filter(asList(sslParameters.getProtocols()), not(in(bannedProtocols))), String.class);
sslParameters.setCipherSuites(cipherSuites);
sslParameters.setProtocols(protocols);
sslParameters.setWantClientAuth(true);
sslParameters.setNeedClientAuth(true);
delegate.setSSLParameters(sslParameters);
ClientGsiEngine engine = new ClientGsiEngine(delegate, credential, isDelegationEnabled, isDelegationLimited);
return new SslEngineDssContext(engine, cf);
} catch (Exception e) {
Throwables.propagateIfPossible(e, IOException.class);
throw new IOException("Failed to create SSL engine: " + e.getMessage(), e);
}
}
Example 26
Project: http2-netty-master File: Http2OrHttpHandler.java View source code |
@Override
protected SelectedProtocol getProtocol(SSLEngine engine) {
String[] protocol = engine.getSession().getProtocol().split(":");
if (protocol != null && protocol.length > 1) {
SelectedProtocol selectedProtocol = SelectedProtocol.protocol(protocol[1]);
//System.err.println("Selected Protocol is " + selectedProtocol);
return selectedProtocol;
}
return SelectedProtocol.UNKNOWN;
}
Example 27
Project: infinispan-master File: HotRodSslFunctionalTest.java View source code |
@Override
protected HotRodClient connectClient() {
SslConfiguration ssl = hotRodServer.getConfiguration().ssl();
SSLContext sslContext = SslContextFactory.getContext(ssl.keyStoreFileName(), ssl.keyStorePassword(), ssl.trustStoreFileName(), ssl.trustStorePassword());
SSLEngine sslEngine = SslContextFactory.getEngine(sslContext, true, false);
return new HotRodClient(host(), hotRodServer.getPort(), cacheName, 60, (byte) 20, sslEngine);
}
Example 28
Project: jetty.project-master File: AliasedX509ExtendedKeyManager.java View source code |
@Override
public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
if (_alias == null)
return _delegate.chooseEngineServerAlias(keyType, issuers, engine);
String[] aliases = _delegate.getServerAliases(keyType, issuers);
if (aliases != null) {
for (String a : aliases) if (_alias.equals(a))
return _alias;
}
return null;
}
Example 29
Project: mini-blog-master File: ProxyServerPipelineFactory.java View source code |
public ChannelPipeline getPipeline() throws Exception {
// Note the static import.
ChannelPipeline p = pipeline();
if (isSLL) {
SSLEngine engine = BogusSslContextFactory.getInstance(true).createSSLEngine();
engine.setUseClientMode(false);
p.addLast("ssl", new SslHandler(engine));
}
p.addLast("encode", new ObjectEncoder());
p.addLast("decode", new ObjectDecoder());
//10秒没有数�读�,则Timeout
//pipleline.addLast("timeout",new ReadTimeoutHandler(new HashedWheelTimer(),10));
p.addLast("executor", executionHandler);
//æ¤ä¸¤é¡¹ä¸ºæ·»åŠ 心跳机制 10秒查看一次在线的客户端channel是å?¦ç©ºé—²ï¼ŒIdleStateHandler为netty jar包ä¸æ??供的类
p.addLast("timeout", new IdleStateHandler(hashedWheelTimer, 0, 10, 0));
//æ¤ç±» 实现了IdleStateAwareChannelHandler接å?£
p.addLast("hearbeat", new Heartbeat());
p.addLast("log", new LoggingHandler(InternalLogLevel.INFO));
p.addLast("handler", new ProxyInServerboundHandler(cf, remoteHost, remotePort));
return p;
}
Example 30
Project: Misc-master File: SecureChatServerPipelineFactory.java View source code |
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
// Add SSL handler first to encrypt and decrypt everything.
// In this example, we use a bogus certificate in the server side
// and accept any invalid certificates in the client side.
// You will need something more complicated to identify both
// and server in the real world.
//
// Read SecureChatSslContextFactory
// if you need client certificate authentication.
SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
// On top of the SSL handler, add the text line codec.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
// and then business logic.
pipeline.addLast("handler", new SecureChatServerHandler());
return pipeline;
}
Example 31
Project: moco-master File: MocoHttpServer.java View source code |
private Function<HttpsCertificate, SslHandler> toSslHandler() {
return new Function<HttpsCertificate, SslHandler>() {
@Override
public SslHandler apply(final HttpsCertificate certificate) {
SSLEngine sslEngine = certificate.createSSLEngine();
sslEngine.setUseClientMode(false);
return new SslHandler(sslEngine);
}
};
}
Example 32
Project: netty-learning-master File: SslCloseTest.java View source code |
/**
* Try to write a testcase to reproduce #343
*/
@Test
public void testCloseOnSslException() {
ServerBootstrap sb = new ServerBootstrap(new NioServerSocketChannelFactory());
ClientBootstrap cb = new ClientBootstrap(new NioClientSocketChannelFactory());
SSLEngine sse = SecureChatSslContextFactory.getServerContext().createSSLEngine();
sse.setUseClientMode(false);
sb.getPipeline().addFirst("ssl", new SslHandler(sse));
sb.getPipeline().addLast("handler", new SimpleChannelUpstreamHandler() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
e.getCause().printStackTrace();
System.out.println("Close channel");
ctx.getChannel().close();
}
});
Channel serverChannel = sb.bind(new InetSocketAddress(0));
Channel cc = cb.connect(serverChannel.getLocalAddress()).awaitUninterruptibly().getChannel();
cc.write(ChannelBuffers.copiedBuffer("unencrypted", CharsetUtil.US_ASCII)).awaitUninterruptibly();
Assert.assertTrue(cc.getCloseFuture().awaitUninterruptibly(5000));
serverChannel.close();
cb.releaseExternalResources();
sb.releaseExternalResources();
}
Example 33
Project: netty4study-master File: SslHandlerTest.java View source code |
@Test
public void testTruncatedPacket() throws Exception {
SSLEngine engine = SSLContext.getDefault().createSSLEngine();
engine.setUseClientMode(false);
EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine));
// Push the first part of a 5-byte handshake message.
ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 22, 3, 1, 0, 5 }));
// Should decode nothing yet.
assertThat(ch.readInbound(), is(nullValue()));
try {
// Push the second part of the 5-byte handshake message.
ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 2, 0, 0, 1, 0 }));
fail();
} catch (DecoderException e) {
assertThat(e.getCause(), is(instanceOf(SSLProtocolException.class)));
}
}
Example 34
Project: openflowjava-master File: SimpleClientInitializer.java View source code |
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (secured) {
SSLEngine engine = ClientSslContextFactory.getClientContext().createSSLEngine();
engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine));
}
SimpleClientHandler simpleClientHandler = new SimpleClientHandler(isOnlineFuture, scenarioHandler);
simpleClientHandler.setScenario(scenarioHandler);
pipeline.addLast("framer", new SimpleClientFramer());
pipeline.addLast("handler", simpleClientHandler);
isOnlineFuture = null;
}
Example 35
Project: openjdk-master File: RehandshakeWithDataExTest.java View source code |
@Override protected void testOneCipher(String cipher) throws SSLException { SSLContext context = getContext(); int maxPacketSize = getMaxPacketSize(); boolean useSNI = !TEST_MODE.equals("norm"); SSLEngine clientEngine = getClientSSLEngine(context, useSNI); SSLEngine serverEngine = getServerSSLEngine(context, useSNI); clientEngine.setEnabledCipherSuites(new String[] { cipher }); serverEngine.setEnabledCipherSuites(new String[] { cipher }); serverEngine.setNeedClientAuth(!cipher.contains("anon")); long initialEpoch = 0; long secondEpoch = 0; long thirdEpoch = 0; SSLEngineResult r; doHandshake(clientEngine, serverEngine, maxPacketSize, HandshakeMode.INITIAL_HANDSHAKE); sendApplicationData(clientEngine, serverEngine); r = sendApplicationData(serverEngine, clientEngine); if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) { initialEpoch = r.sequenceNumber() >> 48; } doHandshake(clientEngine, serverEngine, maxPacketSize, HandshakeMode.REHANDSHAKE_BEGIN_CLIENT); sendApplicationData(clientEngine, serverEngine); r = sendApplicationData(serverEngine, clientEngine); AssertionError epochError = new AssertionError("Epoch number" + " did not grow after re-handshake! " + " Was " + initialEpoch + ", now " + secondEpoch + "."); if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) { secondEpoch = r.sequenceNumber() >> 48; if (Long.compareUnsigned(secondEpoch, initialEpoch) <= 0) { throw epochError; } } doHandshake(clientEngine, serverEngine, maxPacketSize, HandshakeMode.REHANDSHAKE_BEGIN_SERVER); sendApplicationData(clientEngine, serverEngine); r = sendApplicationData(serverEngine, clientEngine); if (TESTED_SECURITY_PROTOCOL.contains("DTLS")) { thirdEpoch = r.sequenceNumber() >> 48; if (Long.compareUnsigned(thirdEpoch, secondEpoch) <= 0) { throw epochError; } } closeEngines(clientEngine, serverEngine); }
Example 36
Project: osgi-maven-master File: SecureChatServerPipelineFactory.java View source code |
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
// Add SSL handler first to encrypt and decrypt everything.
// In this example, we use a bogus certificate in the server side
// and accept any invalid certificates in the client side.
// You will need something more complicated to identify both
// and server in the real world.
//
// Read SecureChatSslContextFactory
// if you need client certificate authentication.
SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
// On top of the SSL handler, add the text line codec.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
// and then business logic.
pipeline.addLast("handler", new SecureChatServerHandler());
return pipeline;
}
Example 37
Project: RestComm-master File: SslHttpServerPipelineFactory.java View source code |
public ChannelPipeline getPipeline() throws Exception {
Integer max = Integer.valueOf(Play.configuration.getProperty("play.netty.maxContentLength", "-1"));
String mode = Play.configuration.getProperty("play.netty.clientAuth", "none");
ChannelPipeline pipeline = pipeline();
// Add SSL handler first to encrypt and decrypt everything.
SSLEngine engine = SslHttpServerContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
if ("want".equalsIgnoreCase(mode)) {
engine.setWantClientAuth(true);
} else if ("need".equalsIgnoreCase(mode)) {
engine.setNeedClientAuth(true);
}
engine.setEnableSessionCreation(true);
pipeline.addLast("flashPolicy", new FlashPolicyHandler());
pipeline.addLast("ssl", new SslHandler(engine));
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new StreamChunkAggregator(max));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("handler", new SslPlayHandler());
return pipeline;
}
Example 38
Project: restcommander-master File: SslHttpServerPipelineFactory.java View source code |
public ChannelPipeline getPipeline() throws Exception {
Integer max = Integer.valueOf(Play.configuration.getProperty("play.netty.maxContentLength", "-1"));
String mode = Play.configuration.getProperty("play.netty.clientAuth", "none");
ChannelPipeline pipeline = pipeline();
// Add SSL handler first to encrypt and decrypt everything.
SSLEngine engine = SslHttpServerContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
if ("want".equalsIgnoreCase(mode)) {
engine.setWantClientAuth(true);
} else if ("need".equalsIgnoreCase(mode)) {
engine.setNeedClientAuth(true);
}
engine.setEnableSessionCreation(true);
pipeline.addLast("flashPolicy", new FlashPolicyHandler());
pipeline.addLast("ssl", new SslHandler(engine));
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new StreamChunkAggregator(max));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("handler", new SslPlayHandler());
return pipeline;
}
Example 39
Project: sissi-master File: FixDomainStartTls.java View source code |
@Override
public boolean startTls(String domain) {
try {
if (this.isTls.compareAndSet(false, true)) {
SSLEngine engine = this.sslContextBuilder.build().createSSLEngine();
engine.setNeedClientAuth(false);
engine.setUseClientMode(false);
this.handler = new SslHandler(engine);
this.prepareTls.compareAndSet(false, true);
}
return true;
} catch (Exception e) {
log.error(e.toString());
Trace.trace(log, e);
return this.rollbackSSL();
}
}
Example 40
Project: streamline-master File: SecureChatServerPipelineFactory.java View source code |
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
// Add SSL handler first to encrypt and decrypt everything.
// In this example, we use a bogus certificate in the server side
// and accept any invalid certificates in the client side.
// You will need something more complicated to identify both
// and server in the real world.
//
// Read SecureChatSslContextFactory
// if you need client certificate authentication.
SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
// On top of the SSL handler, add the text line codec.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
// and then business logic.
pipeline.addLast("handler", new SecureChatServerHandler());
return pipeline;
}
Example 41
Project: voltdb-master File: VoltPortFactory.java View source code |
public static VoltPort createVoltPort(final SocketChannel channel, final VoltNetwork network, final InputHandler handler, final InetSocketAddress remoteAddress, final NetworkDBBPool pool, final CipherExecutor cipherExecutor, final SSLEngine sslEngine) {
if (sslEngine == null) {
return new VoltPort(network, handler, (InetSocketAddress) channel.socket().getRemoteSocketAddress(), pool);
} else {
return new TLSVoltPort(network, handler, (InetSocketAddress) channel.socket().getRemoteSocketAddress(), pool, sslEngine, cipherExecutor);
}
}
Example 42
Project: wildfly-swarm-master File: HTTP2Customizer.java View source code |
protected boolean supportsHTTP2() {
try {
SSLContext context = SSLContext.getDefault();
SSLEngine engine = context.createSSLEngine();
String[] ciphers = engine.getEnabledCipherSuites();
for (String i : ciphers) {
if (i.equals(REQUIRED_CIPHER)) {
return true;
}
}
} catch (NoSuchAlgorithmException e) {
}
return false;
}
Example 43
Project: xnio-master File: JsseAcceptingSslStreamConnection.java View source code |
@Override
public SslConnection accept(StreamConnection tcpConnection, SSLEngine engine) throws IOException {
if (!JsseXnioSsl.NEW_IMPL) {
return new JsseSslStreamConnection(tcpConnection, engine, socketBufferPool, applicationBufferPool, startTls);
}
JsseSslConnection connection = new JsseSslConnection(tcpConnection, engine, socketBufferPool, applicationBufferPool);
if (!startTls) {
try {
connection.startHandshake();
} catch (IOException e) {
IoUtils.safeClose(connection);
throw e;
}
}
return connection;
}
Example 44
Project: apn-proxy-master File: ApnProxyRemoteForwardChannelInitializer.java View source code |
@Override
public void initChannel(SocketChannel channel) throws Exception {
ApnProxyRemote apnProxyRemote = uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get().getRemote();
channel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).set(uaChannel.attr(ApnProxyConnectionAttribute.ATTRIBUTE_KEY).get());
ChannelPipeline pipeline = channel.pipeline();
pipeline.addLast("idlestate", new IdleStateHandler(0, 0, 3, TimeUnit.MINUTES));
pipeline.addLast("idlehandler", new ApnProxyIdleHandler());
if (apnProxyRemote.getRemoteListenType() == ApnProxyListenType.SSL) {
SSLEngine engine = ApnProxySSLContextFactory.createClientSSLEnginForRemoteAddress(apnProxyRemote.getRemoteHost(), apnProxyRemote.getRemotePort());
engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine));
} else if (apnProxyRemote.getRemoteListenType() == ApnProxyListenType.AES) {
byte[] key = ((ApnProxyAESRemote) apnProxyRemote).getKey();
byte[] iv = ((ApnProxyAESRemote) apnProxyRemote).getIv();
pipeline.addLast("apnproxy.encrypt", new ApnProxyAESEncoder(key, iv));
pipeline.addLast("apnproxy.decrypt", new ApnProxyAESDecoder(key, iv));
}
pipeline.addLast("codec", new HttpClientCodec());
pipeline.addLast(ApnProxyRemoteForwardHandler.HANDLER_NAME, new ApnProxyRemoteForwardHandler(uaChannel, remoteChannelInactiveCallback));
}
Example 45
Project: bonaparte-java-master File: BonaparteNettySslPipelineFactory.java View source code |
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (useSsl) {
// create the SSL engine
SSLEngine engine = NettySslContextFactory.getServerContext().createSSLEngine();
engine.setUseClientMode(clientMode);
engine.setNeedClientAuth(needClientAuth);
// add ssl to pipeline first, as in the SecureChat example
pipeline.addLast("ssl", new SslHandler(engine));
}
// Add the text line codec combination first,
pipeline.addLast("framer", new LineBasedFrameDecoder(maximumMessageLength, false, false));
// transmission serialization format
pipeline.addLast("decoder", new BonaparteNettyDecoder(errorForwarder));
pipeline.addLast("encoder", new BonaparteNettyEncoder());
// and then business logic.
if (databaseWorkerThreadPool != null)
// separate worker pool
pipeline.addLast(databaseWorkerThreadPool, "handler", objectHandler);
else
// do it in the I/O thread
pipeline.addLast("handler", objectHandler);
}
Example 46
Project: camel-master File: LumberjackUtil.java View source code |
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
if (sslContextParameters != null) {
SSLEngine sslEngine = sslContextParameters.createSSLContext(null).createSSLEngine();
sslEngine.setUseClientMode(true);
pipeline.addLast(new SslHandler(sslEngine));
}
// Add the response recorder
pipeline.addLast(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
assertEquals(msg.readUnsignedByte(), (short) '2');
assertEquals(msg.readUnsignedByte(), (short) 'A');
synchronized (responses) {
responses.add(msg.readInt());
}
}
});
}
Example 47
Project: carbon-transports-master File: HTTPServerInitializer.java View source code |
@Override
protected void initChannel(Channel channel) throws Exception {
ChannelPipeline p = channel.pipeline();
if (sslContext != null) {
SSLEngine engine = sslContext.createSSLEngine();
engine.setUseClientMode(false);
p.addLast("ssl", new SslHandler(engine));
}
p.addLast("decoder", new HttpRequestDecoder());
p.addLast("encoder", new HttpResponseEncoder());
HTTPServerHandler httpServerHandler = new HTTPServerHandler();
httpServerHandler.setMessage(message, contentType);
httpServerHandler.setResponseStatusCode(responseCode);
p.addLast("handler", httpServerHandler);
}
Example 48
Project: graylog2-input-lumberjack-master File: LumberjackServer.java View source code |
private SSLEngine getSSLEngine() throws GeneralSecurityException, IOException { SSLContext context; char[] storepass = configuration.getKeyStorePass().toCharArray(); char[] keypass = configuration.getKeyPass().toCharArray(); String storePath = configuration.getKeyStorePath(); try { context = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); FileInputStream fin = new FileInputStream(storePath); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(fin, storepass); kmf.init(ks, keypass); context.init(kmf.getKeyManagers(), null, null); } catch (GeneralSecurityExceptionIOException | e) { LOGGER.warn("Exception while creating channel pipeline", e); throw e; } SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(false); return engine; }
Example 49
Project: http-kit-master File: HttpsClientTest.java View source code |
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = new HttpClient();
String[] urls = new String[] { "https://localhost:9898/spec" };
ExecutorService pool = Executors.newCachedThreadPool();
for (String url : urls) {
final CountDownLatch cd = new CountDownLatch(1);
SSLEngine engine = SslContextFactory.getClientContext().createSSLEngine();
RequestConfig cfg = new RequestConfig(HttpMethod.POST, null, null, 40000, 40000, -1, null, false);
TreeMap<String, Object> headers = new TreeMap<String, Object>();
for (int i = 0; i < 33; i++) {
headers.put("X-long-header" + i, AGENT + AGENT + AGENT + AGENT);
}
headers.put("User-Agent", AGENT);
StringBuilder body = new StringBuilder(16 * 1024);
for (int i = 0; i < 16 * 1024; ++i) {
body.append(i);
}
client.exec(url, cfg, null, new RespListener(new IResponseHandler() {
public void onSuccess(int status, Map<String, Object> headers, Object body) {
int length = body instanceof String ? ((String) body).length() : ((BytesInputStream) body).available();
System.out.println(body);
logger.info("{}, {}, {}", status, headers, length);
cd.countDown();
}
public void onThrowable(Throwable t) {
logger.error("error", t);
cd.countDown();
}
}, IFilter.ACCEPT_ALL, pool, 1));
cd.await();
}
}
Example 50
Project: iSocket-master File: ClientSSLFilter.java View source code |
/**
* Once SSL handshake will be completed - send greeting message
*/
@Override
public void completed(SSLEngine result) {
try {
//connection.write(MESSAGE);
if (logger.isDebugEnabled()) {
logger.debug("handshake status:{}", result.getHandshakeStatus());
}
resultFuture.result(result.getHandshakeStatus());
} catch (Exception e) {
try {
connection.close();
} catch (IOException ex) {
}
}
}
Example 51
Project: java-loggregator-master File: LoggregatorClient.java View source code |
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
final ChannelPipeline pipeline = socketChannel.pipeline();
final SSLEngine engine = SSLContext.getDefault().createSSLEngine();
engine.setUseClientMode(true);
pipeline.addFirst("ssl", new SslHandler(engine)).addLast("http-codec", new HttpClientCodec()).addLast("aggregator", new HttpObjectAggregator(8192)).addLast("ws-handler", new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (msg instanceof BinaryWebSocketFrame) {
final BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
final ByteBufInputStream in = new ByteBufInputStream(frame.content());
final Messages.LogMessage logMessage = Messages.LogMessage.parseFrom(in);
System.out.println(logMessage);
} else {
System.out.println("Received unexpected object: " + msg);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
}
});
}
Example 52
Project: jdk7u-jdk-master File: AcceptLargeFragments.java View source code |
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 "); } }
Example 53
Project: jlibs-master File: HTTPProxy.java View source code |
@Override
public void completed(ClientExchange exchange, Throwable thr) {
if (thr == null) {
Connection con = exchange.stealConnection();
try {
if (endpoint.sslContext != null) {
SSLEngine engine = endpoint.sslContext.createSSLEngine();
engine.setUseClientMode(true);
new SSLSocket(con.in(), con.out(), engine);
}
} catch (Throwable thr1) {
con.close();
listener.accept(new Result<>(thr1));
return;
}
listener.accept(new Result<>(con));
} else
listener.accept(new Result<>(thr));
}
Example 54
Project: kazeproxy-master File: KazeProxy.java View source code |
protected ChainedProxy newChainedProxy() {
return new ChainedProxyAdapter() {
@Override
public TransportProtocol getTransportProtocol() {
return TransportProtocol.TCP;
}
@Override
public boolean requiresEncryption() {
return true;
}
@Override
public SSLEngine newSslEngine() {
SslEngineSource sslEngineSource = new KazeSslEngineSource("kclient.jks", "tclient.jks", false, true, "serverkey", jkspw);
return sslEngineSource.newSslEngine();
}
@Override
public InetSocketAddress getChainedProxyAddress() {
try {
return new InetSocketAddress(InetAddress.getByName(serverIp), serverPort);
} catch (UnknownHostException uhe) {
throw new RuntimeException("Unable to resolve " + serverIp);
}
}
};
}
Example 55
Project: kinetic-java-master File: TlsUtil.java View source code |
/** * * Configure the TLS/SSL engine to support the specified protocols. * <P> * The current supported protocols are "TLSv1", "TLSv1.1", "TLSv1.2". * <p> * * @param engine * the TLS engine to be configured. * * @see SSLEngine */ public static void enableSupportedProtocols(SSLEngine engine) { try { // set enabled protocols engine.setEnabledProtocols(SUPPORTED_TLS_PROTOCOLS); logger.info("enabled TLS protocol: " + supportedTLSString); } catch (Exception e) { logger.warning("Failed to enable TLS protocols. Possible fix is to use Java 1.7 or later."); logger.log(Level.WARNING, e.getMessage(), e); } }
Example 56
Project: kraken-master File: AcceptorI.java View source code |
public IceInternal.Transceiver accept() {
//
if (!_instance.initialized()) {
Ice.PluginInitializationException ex = new Ice.PluginInitializationException();
ex.reason = "IceSSL: plug-in is not initialized";
throw ex;
}
java.nio.channels.SocketChannel fd = IceInternal.Network.doAccept(_fd);
javax.net.ssl.SSLEngine engine = null;
try {
IceInternal.Network.setBlock(fd, false);
IceInternal.Network.setTcpBufSize(fd, _instance.communicator().getProperties(), _logger);
engine = _instance.createSSLEngine(true);
} catch (RuntimeException ex) {
IceInternal.Network.closeSocketNoThrow(fd);
throw ex;
}
if (_instance.networkTraceLevel() >= 1) {
_logger.trace(_instance.networkTraceCategory(), "accepting ssl connection\n" + IceInternal.Network.fdToString(fd));
}
return new TransceiverI(_instance, engine, fd, "", true, true, _adapterName);
}
Example 57
Project: LittleProxy-mitm-master File: CertificateSniffingMitmManager.java View source code |
public SSLEngine clientSslEngineFor(HttpRequest httpRequest, SSLSession serverSslSession) {
try {
X509Certificate upstreamCert = getCertificateFromSession(serverSslSession);
// TODO store the upstream cert by commonName to review it later
// A reasons to not use the common name and the alternative names
// from upstream certificate from serverSslSession to create the
// dynamic certificate:
//
// It's not necessary. The host name is accepted by the browser.
//
String commonName = getCommonName(upstreamCert);
SubjectAlternativeNameHolder san = new SubjectAlternativeNameHolder();
san.addAll(upstreamCert.getSubjectAlternativeNames());
LOG.debug("Subject Alternative Names: {}", san);
return sslEngineSource.createCertForHost(commonName, san);
} catch (Exception e) {
throw new FakeCertificateException("Creation dynamic certificate failed", e);
}
}
Example 58
Project: ManagedRuntimeInitiative-master File: AcceptLargeFragments.java View source code |
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 "); } }
Example 59
Project: minnal-master File: HttpsConnector.java View source code |
/**
* @return
*/
protected SSLEngine createSslEngine() {
logger.debug("Creating a SSL engine from the SSL context");
String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
if (algorithm == null) {
algorithm = "SunX509";
logger.trace("ssl.KeyManagerFactory.algorithm algorithm is not set. Defaulting to {}", algorithm);
}
SSLContext serverContext = null;
SSLConfiguration configuration = getConnectorConfiguration().getSslConfiguration();
InputStream stream = null;
try {
File file = new File(configuration.getKeyStoreFile());
stream = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(configuration.getKeystoreType());
ks.load(stream, configuration.getKeyStorePassword().toCharArray());
// Set up key manager factory to use our key store
KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
kmf.init(ks, configuration.getKeyPassword().toCharArray());
// Initialize the SSLContext to work with our key managers.
serverContext = SSLContext.getInstance(configuration.getProtocol());
serverContext.init(kmf.getKeyManagers(), null, null);
} catch (Exception e) {
logger.error("Failed while initializing the ssl context", e);
throw new MinnalException("Failed to initialize the ssl context", e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
logger.trace("Failed while closing the stream", e);
}
}
}
return serverContext.createSSLEngine();
}
Example 60
Project: nettosphere-master File: NettyChannelInitializer.java View source code |
@Override
protected void initChannel(Channel ch) throws Exception {
final ChannelPipeline pipeline = ch.pipeline();
if (config.sslContext() != null) {
SSLEngine e = config.sslContext().createSSLEngine();
config.sslContextListener().onPostCreate(e);
pipeline.addLast("ssl", new SslHandler(e));
}
if (config.nettySslContext() != null) {
pipeline.addLast("ssl", config.nettySslContext().newHandler(ch.alloc()));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpObjectAggregator(config.maxChunkContentLength()));
if (config.supportChunking()) {
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
}
for (ChannelInboundHandler h : config.channelUpstreamHandlers()) {
pipeline.addLast(h.getClass().getName(), h);
}
pipeline.addLast(new WebSocketServerCompressionHandler());
pipeline.addLast(BridgeRuntime.class.getName(), bridgeRuntime);
}
Example 61
Project: netty4.0.27Learn-master File: SslHandlerTest.java View source code |
@Test
public void testTruncatedPacket() throws Exception {
SSLEngine engine = SSLContext.getDefault().createSSLEngine();
engine.setUseClientMode(false);
EmbeddedChannel ch = new EmbeddedChannel(new SslHandler(engine));
// Push the first part of a 5-byte handshake message.
ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 22, 3, 1, 0, 5 }));
// Should decode nothing yet.
assertThat(ch.readInbound(), is(nullValue()));
try {
// Push the second part of the 5-byte handshake message.
ch.writeInbound(Unpooled.wrappedBuffer(new byte[] { 2, 0, 0, 1, 0 }));
fail();
} catch (DecoderException e) {
assertThat(e.getCause(), is(instanceOf(SSLProtocolException.class)));
}
}
Example 62
Project: nifty-master File: OpenSslSessionHelper.java View source code |
public static SslSession getSession(SSLEngine sslEngine) throws SSLException {
if (!(sslEngine instanceof OpenSslEngine)) {
throw new IllegalArgumentException("ssl engine not openssl engine");
}
OpenSslEngine engine = (OpenSslEngine) sslEngine;
if (sslField == null) {
throw new SSLException("SSL field is null");
}
try {
long sslPtr = (long) sslField.get(engine);
if (sslPtr == 0) {
throw new SSLException("SSL not initialized");
}
String alpn = SSL.getAlpnSelected(sslPtr);
String npn = SSL.getNextProtoNegotiated(sslPtr);
String version = SSL.getVersion(sslPtr);
String cipher = SSL.getCipherForSSL(sslPtr);
long establishedTime = SSL.getTime(sslPtr);
// TODO: return the entire chain.
// tc-native thinks that the chain is null, so we supply only the
// leaf cert.
byte[] cert = SSL.getPeerCertificate(sslPtr);
X509Certificate certificate = null;
if (cert != null) {
certificate = X509Certificate.getInstance(cert);
}
return new SslSession(alpn, npn, version, cipher, establishedTime, certificate);
} catch (IllegalAccessException e) {
throw new SSLException(e);
} catch (CertificateException e) {
throw new SSLException(e);
}
}
Example 63
Project: openjdk8-jdk-master File: AcceptLargeFragments.java View source code |
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 "); } }
Example 64
Project: spring-integration-master File: DefaultTcpNioSSLConnectionSupport.java View source code |
/**
* Creates a {@link TcpNioSSLConnection}.
*/
@Override
public TcpNioConnection createNewConnection(SocketChannel socketChannel, boolean server, boolean lookupHost, ApplicationEventPublisher applicationEventPublisher, String connectionFactoryName) throws Exception {
SSLEngine sslEngine = this.sslContext.createSSLEngine();
postProcessSSLEngine(sslEngine);
TcpNioSSLConnection tcpNioSSLConnection = new TcpNioSSLConnection(socketChannel, server, lookupHost, applicationEventPublisher, connectionFactoryName, sslEngine);
tcpNioSSLConnection.init();
return tcpNioSSLConnection;
}
Example 65
Project: ssl_npn-master File: AcceptLargeFragments.java View source code |
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 "); } }
Example 66
Project: strest-server-master File: StrestServerPipelineFactory.java View source code |
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
if (this.sslContext != null) {
SSLEngine engine = this.sslContext.createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
pipeline.addLast("aggregator", new StrestChunkAggregator(65536));
pipeline.addLast("encoder", new HttpResponseEncoder());
// Remove the following line if you don't want automatic content compression.
pipeline.addLast("deflater", new StrestResponseEncoder());
pipeline.addLast("executionHandler", handler);
pipeline.addLast("handler", new StrestRequestHandler(router));
return pipeline;
}
Example 67
Project: tomcat70-master File: Jre8Compat.java View source code |
@Override
public void setUseServerCipherSuitesOrder(SSLEngine engine, boolean useCipherSuitesOrder) {
SSLParameters sslParameters = engine.getSSLParameters();
try {
setUseCipherSuitesOrderMethod.invoke(sslParameters, Boolean.valueOf(useCipherSuitesOrder));
engine.setSSLParameters(sslParameters);
} catch (IllegalArgumentException e) {
throw new UnsupportedOperationException(e);
} catch (IllegalAccessException e) {
throw new UnsupportedOperationException(e);
} catch (InvocationTargetException e) {
throw new UnsupportedOperationException(e);
}
}
Example 68
Project: user-master File: WebSocketServerPipelineFactory.java View source code |
@Override
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
if (ssl) {
SSLEngine sslEngine = WebSocketSslContextFactory.getServerContext().createSSLEngine();
sslEngine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(sslEngine));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("execution", executionHandler);
pipeline.addLast("handler", new WebSocketChannelHandler(emf, smf, management, securityManager, ssl));
return pipeline;
}
Example 69
Project: usergrid-master File: WebSocketServerPipelineFactory.java View source code |
@Override
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
if (ssl) {
SSLEngine sslEngine = WebSocketSslContextFactory.getServerContext().createSSLEngine();
sslEngine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(sslEngine));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("execution", executionHandler);
pipeline.addLast("handler", new WebSocketChannelHandler(emf, smf, management, securityManager, ssl));
return pipeline;
}
Example 70
Project: wildfly-elytron-master File: ConfiguredSSLContextSpi.java View source code |
protected SSLEngine engineCreateSSLEngine(final String host, final int port) { final SSLEngine sslEngine = super.engineCreateSSLEngine(host, port); final SSLConfigurator sslConfigurator = this.sslConfigurator; sslConfigurator.configure(getDelegate(), sslEngine); return wrap ? new ConfiguredSSLEngine(sslEngine, getDelegate(), sslConfigurator) : sslEngine; }
Example 71
Project: wildfly-security-master File: ConfiguredSSLContextSpi.java View source code |
protected SSLEngine engineCreateSSLEngine(final String host, final int port) { final SSLEngine sslEngine = super.engineCreateSSLEngine(host, port); final SSLConfigurator sslConfigurator = this.sslConfigurator; sslConfigurator.configure(getDelegate(), sslEngine); return wrap ? new ConfiguredSSLEngine(sslEngine, getDelegate(), sslConfigurator) : sslEngine; }
Example 72
Project: wso2-synapse-master File: ServerSSLSetupHandler.java View source code |
public void initalize(final SSLEngine sslengine) throws SSLException {
if (clientAuth != null) {
switch(clientAuth) {
case OPTIONAL:
sslengine.setWantClientAuth(true);
break;
case REQUIRED:
sslengine.setNeedClientAuth(true);
}
}
// configuration.
if (httpsProtocols != null) {
sslengine.setEnabledProtocols(httpsProtocols);
}
}
Example 73
Project: 2FactorWallet-master File: TLSClientHelper.java View source code |
@Override
public SocketChannel newChannel(ChannelPipeline pipeline) {
try {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, new TrustManager[] { new BogusTrustManager(publicKey) }, null);
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setUseClientMode(true);
pipeline.addFirst("ssl", new SslHandler(sslEngine));
return super.newChannel(pipeline);
} catch (Exception ex) {
throw new RuntimeException("Cannot create SSL channel", ex);
}
}
Example 74
Project: archistar-core-master File: ServerServerCommunication.java View source code |
@Override
public void initChannel(SocketChannel ch) throws Exception {
// enable SSL/TLS support
SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
engine.setUseClientMode(true);
ch.pipeline().addLast(new SslHandler(engine), new ObjectEncoder(), new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)));
}
Example 75
Project: argus-pdp-pep-common-master File: JettySslSelectChannelConnector.java View source code |
/** * Disable the all ECDH cipher suites because of the OpenSSL 1.0 problem * with SSL handshake. * <p> * {@inheritDoc} */ protected SSLEngine createSSLEngine() throws IOException { SSLEngine sslEngine = super.createSSLEngine(); String enabledCipherSuites[] = sslEngine.getEnabledCipherSuites(); List<String> cipherSuites = new ArrayList<String>(Arrays.asList(enabledCipherSuites)); for (String cipher : enabledCipherSuites) { if (cipher.contains("ECDH")) { log.debug("disabling cipher: {}", cipher); cipherSuites.remove(cipher); } } log.debug("enabling ciphers: {}", cipherSuites); enabledCipherSuites = (String[]) cipherSuites.toArray(new String[cipherSuites.size()]); sslEngine.setEnabledCipherSuites(enabledCipherSuites); return sslEngine; }
Example 76
Project: blade-master File: SslClientConnectionFactory.java View source code |
@Override
public Connection newConnection(EndPoint endPoint, Map<String, Object> context) throws IOException {
String host = (String) context.get(SSL_PEER_HOST_CONTEXT_KEY);
int port = (Integer) context.get(SSL_PEER_PORT_CONTEXT_KEY);
SSLEngine engine = sslContextFactory.newSSLEngine(host, port);
engine.setUseClientMode(true);
context.put(SSL_ENGINE_CONTEXT_KEY, engine);
SslConnection sslConnection = newSslConnection(byteBufferPool, executor, endPoint, engine);
endPoint.setConnection(sslConnection);
customize(sslConnection, context);
EndPoint appEndPoint = sslConnection.getDecryptedEndPoint();
appEndPoint.setConnection(connectionFactory.newConnection(appEndPoint, context));
return sslConnection;
}
Example 77
Project: chililog-server-master File: HttpServerPipelineFactory.java View source code |
/**
* Creates an HTTP Pipeline for our server
*/
public ChannelPipeline getPipeline() throws Exception {
AppProperties appProperties = AppProperties.getInstance();
// Create a default pipeline implementation.
ChannelPipeline pipeline = pipeline();
// SSL handling
if (appProperties.getWorkbenchSslEnabled()) {
SSLEngine engine = SslContextManager.getInstance().getServerContext().createSSLEngine();
engine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(engine));
}
// Decodes ChannelBuffer into HTTP Request message
pipeline.addLast("decoder", new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
// Leave it off. We want to handle large file uploads efficiently by not aggregating and storing in memory
// pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
// Encodes HTTTPRequest message to ChannelBuffer
pipeline.addLast("encoder", new HttpResponseEncoder());
// Chunked handler for SSL large static file downloads
if (appProperties.getWorkbenchSslEnabled()) {
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
}
// Compress
pipeline.addLast("deflater", new HttpContentCompressor(1));
// Execute the handler in a new thread
pipeline.addLast("pipelineExecutor", new ExecutionHandler(_pipelineExecutor));
// Handler to dispatch processing to our services
pipeline.addLast("handler", new HttpRequestHandler());
return pipeline;
}
Example 78
Project: CloudStack-archive-master File: NioClient.java View source code |
@Override
protected void init() throws IOException {
_selector = Selector.open();
SocketChannel sch = null;
InetSocketAddress addr = null;
try {
sch = SocketChannel.open();
sch.configureBlocking(true);
s_logger.info("Connecting to " + _host + ":" + _port);
if (_bindAddress != null) {
s_logger.info("Binding outbound interface at " + _bindAddress);
addr = new InetSocketAddress(_bindAddress, 0);
sch.socket().bind(addr);
}
addr = new InetSocketAddress(_host, _port);
sch.connect(addr);
} catch (IOException e) {
_selector.close();
throw e;
}
SSLEngine sslEngine = null;
try {
// Begin SSL handshake in BLOCKING mode
sch.configureBlocking(true);
SSLContext sslContext = Link.initSSLContext(true);
sslEngine = sslContext.createSSLEngine(_host, _port);
sslEngine.setUseClientMode(true);
Link.doHandshake(sch, sslEngine, true);
s_logger.info("SSL: Handshake done");
} catch (Exception e) {
_selector.close();
throw new IOException("SSL: Fail to init SSL! " + e);
}
Task task = null;
try {
sch.configureBlocking(false);
Link link = new Link(addr, this);
link.setSSLEngine(sslEngine);
SelectionKey key = sch.register(_selector, SelectionKey.OP_READ);
link.setKey(key);
key.attach(link);
// Notice we've already connected due to the handshake, so let's get the
// remaining task done
task = _factory.create(Task.Type.CONNECT, link, null);
} catch (Exception e) {
_selector.close();
throw new IOException("Fail to init NioClient! " + e);
}
_executor.execute(task);
}
Example 79
Project: cloudstack-master File: NioClient.java View source code |
@Override
protected void init() throws IOException {
_selector = Selector.open();
Task task = null;
try {
_clientConnection = SocketChannel.open();
s_logger.info("Connecting to " + _host + ":" + _port);
final InetSocketAddress peerAddr = new InetSocketAddress(_host, _port);
_clientConnection.connect(peerAddr);
_clientConnection.configureBlocking(false);
final SSLContext sslContext = Link.initSSLContext(true);
SSLEngine sslEngine = sslContext.createSSLEngine(_host, _port);
sslEngine.setUseClientMode(true);
sslEngine.setEnabledProtocols(SSLUtils.getSupportedProtocols(sslEngine.getEnabledProtocols()));
sslEngine.beginHandshake();
if (!Link.doHandshake(_clientConnection, sslEngine, true)) {
s_logger.error("SSL Handshake failed while connecting to host: " + _host + " port: " + _port);
_selector.close();
throw new IOException("SSL Handshake failed while connecting to host: " + _host + " port: " + _port);
}
s_logger.info("SSL: Handshake done");
s_logger.info("Connected to " + _host + ":" + _port);
final Link link = new Link(peerAddr, this);
link.setSSLEngine(sslEngine);
final SelectionKey key = _clientConnection.register(_selector, SelectionKey.OP_READ);
link.setKey(key);
key.attach(link);
// Notice we've already connected due to the handshake, so let's get the
// remaining task done
task = _factory.create(Task.Type.CONNECT, link, null);
} catch (final GeneralSecurityException e) {
_selector.close();
throw new IOException("Failed to initialise security", e);
} catch (final IOException e) {
_selector.close();
throw e;
}
_executor.submit(task);
}
Example 80
Project: featured-mock-master File: FeaturedHttpServerBuilder.java View source code |
public FeaturedHttpServer build() {
final SSLEngine engine;
if (ssl) {
SSLContext clientContext;
try {
clientContext = SSLContext.getInstance(protocol);
clientContext.init(keyManagers, trustManagers, secureRandom);
} catch (final Exception e) {
throw new Error("Failed to initialize the client-side SSLContext", e);
}
engine = clientContext.createSSLEngine();
engine.setUseClientMode(true);
} else {
engine = null;
}
return new DefaultFeaturedHttpServer(host, port, threads, mappers.toArray(new ContentTypeMapper[mappers.size()]), engine, observer);
}
Example 81
Project: hadoop-release-2.6.0-master File: SslSelectChannelConnectorSecure.java View source code |
/** * Disable SSLv3 protocol. */ @Override protected SSLEngine createSSLEngine() throws IOException { SSLEngine engine = super.createSSLEngine(); ArrayList<String> nonSSLProtocols = new ArrayList<String>(); for (String p : engine.getEnabledProtocols()) { if (!p.contains("SSLv3")) { nonSSLProtocols.add(p); } } engine.setEnabledProtocols(nonSSLProtocols.toArray(new String[nonSSLProtocols.size()])); return engine; }
Example 82
Project: hivemq-spi-master File: DefaultSslEngineUtil.java View source code |
/**
* Returns a list of all supported Cipher Suites of the JVM.
*
* @return a list of all supported cipher suites of the JVM
* @throws SslException
*/
@ReadOnly
public List<String> getSupportedCipherSuites() throws SslException {
try {
final SSLEngine engine = getDefaultSslEngine();
return ImmutableList.copyOf(engine.getSupportedCipherSuites());
} catch (NoSuchAlgorithmExceptionKeyManagementException | e) {
throw new SslException("Not able to get list of supported cipher suites from JVM", e);
}
}
Example 83
Project: IngotEngine-master File: HttpPostRequest.java View source code |
protected void initChannel(SocketChannel channel) throws Exception {
channel.pipeline().addLast(new ReadTimeoutHandler(10));
SSLContext ssl = SSLContext.getInstance("TLS");
ssl.init(null, new TrustManager[] { DummyTrustManager.instance }, null);
SSLEngine engine = ssl.createSSLEngine();
engine.setUseClientMode(true);
channel.pipeline().addLast(new SslHandler(engine));
channel.pipeline().addLast(new HttpClientCodec());
channel.pipeline().addLast(new SimpleChannelInboundHandler<HttpObject>() {
public void exceptionCaught(ChannelHandlerContext context, Throwable cause) {
HttpPostRequest.this.handler.onError(context.channel(), cause);
}
protected void messageReceived(ChannelHandlerContext context, HttpObject httpObject) throws Exception {
if (httpObject instanceof HttpResponse) {
HttpResponse resp = (HttpResponse) httpObject;
if (resp.getStatus().code() == HttpResponseStatus.NO_CONTENT.code()) {
HttpPostRequest.this.handler.onSuccess(context, "");
} else if (resp.getStatus().code() != HttpResponseStatus.OK.code()) {
HttpPostRequest.this.handler.onError(context.channel(), new Exception("Got incorrect status code!"));
}
} else if (httpObject instanceof HttpContent) {
HttpContent content = (HttpContent) httpObject;
response.append(content.content().toString(Charset.forName("UTF-8")));
if (content instanceof LastHttpContent) {
HttpPostRequest.this.handler.onSuccess(context, response.toString());
}
}
}
});
}
Example 84
Project: java-driver-master File: RemoteEndpointAwareJdkSSLOptions.java View source code |
/** * Creates an SSL engine each time a connection is established. * <p/> * You might want to override this if you need to fine-tune the engine's configuration * (for example enabling hostname verification). * * @param channel the Netty channel for that connection. * @param remoteEndpoint the remote endpoint we are connecting to. * @return the engine. * @since 3.2.0 */ protected SSLEngine newSSLEngine(@SuppressWarnings("unused") SocketChannel channel, InetSocketAddress remoteEndpoint) { SSLEngine engine = remoteEndpoint == null ? context.createSSLEngine() : context.createSSLEngine(remoteEndpoint.getHostName(), remoteEndpoint.getPort()); engine.setUseClientMode(true); if (cipherSuites != null) engine.setEnabledCipherSuites(cipherSuites); return engine; }
Example 85
Project: jdiameter-master File: StartTlsServerHandler.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
logger.debug("StartTlsServerHandler");
ByteBuf buf = (ByteBuf) msg;
byte[] bytes = new byte[buf.readableBytes()];
buf.getBytes(buf.readerIndex(), bytes);
if ("StartTlsRequest".equals(new String(bytes))) {
logger.debug("Received StartTlsRequest");
SslContext sslContext = SslContextFactory.getSslContextForServer(this.tlsTransportClient.getConfig());
SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
sslEngine.setUseClientMode(false);
SslHandler sslHandler = new SslHandler(sslEngine, false);
final ChannelPipeline pipeline = ctx.pipeline();
pipeline.remove("decoder");
pipeline.remove("msgHandler");
pipeline.remove("encoder");
pipeline.remove("inbandWriter");
pipeline.remove(this);
pipeline.addLast("sslHandler", sslHandler);
sslHandler.handshakeFuture().addListener(new GenericFutureListener() {
@Override
public void operationComplete(Future future) throws Exception {
if (future.isSuccess()) {
logger.debug("StartTls server handshake succesfull");
tlsTransportClient.setTlsHandshakingState(TlsHandshakingState.SHAKEN);
logger.debug("restoring all handlers");
pipeline.addLast("decoder", new DiameterMessageDecoder(StartTlsServerHandler.this.tlsTransportClient.getParent(), StartTlsServerHandler.this.tlsTransportClient.getParser()));
pipeline.addLast("msgHandler", new DiameterMessageHandler(StartTlsServerHandler.this.tlsTransportClient.getParent(), true));
pipeline.addLast("encoder", new DiameterMessageEncoder(StartTlsServerHandler.this.tlsTransportClient.getParser()));
pipeline.addLast("inbandWriter", new InbandSecurityHandler());
}
}
});
ReferenceCountUtil.release(msg);
logger.debug("Sending StartTlsResponse");
ctx.writeAndFlush(Unpooled.wrappedBuffer("StartTlsResponse".getBytes())).addListener(new GenericFutureListener() {
@Override
public void operationComplete(Future f) throws Exception {
if (!f.isSuccess()) {
logger.error(f.cause().getMessage(), f.cause());
}
}
});
} else {
ctx.fireChannelRead(msg);
}
}
Example 86
Project: jucy-master File: CryptoInfo.java View source code |
public void setInfo(SSLEngine ssle) {
cryptoInfo.clear();
put(ENABLED_CIPHERSUITES, GH.concat(ssle.getEnabledCipherSuites(), ", ", "-"));
put(ENABLED_PROTOCOLS, GH.concat(ssle.getEnabledProtocols(), ", ", "-"));
put(HADNSHAKE_STATUS, ssle.getHandshakeStatus().toString());
SSLSession ssls = ssle.getSession();
try {
put(PEER_CERTIFICATES, GH.concat(ssls.getPeerCertificates(), "\n---NEW CERT-------\n", "-"));
put(PRINCIPAL, ssls.getPeerPrincipal().toString());
} catch (SSLPeerUnverifiedException e) {
logger.debug(e, e);
}
List<String> keyValuePairs = new ArrayList<String>();
for (String s : ssls.getValueNames()) {
keyValuePairs.add(s + "=" + ssls.getValue(s));
}
put(SESSION_VALUES, GH.concat(keyValuePairs, ", ", "-"));
put(CIPHERSUITE, ssls.getCipherSuite());
put(PROTOCOL, ssls.getProtocol());
put(APPLICATION_BUFFER, SizeEnum.getReadableSize(ssls.getApplicationBufferSize()) + " (" + ssls.getApplicationBufferSize() + ")");
put(PACKET_BUFFER, SizeEnum.getReadableSize(ssls.getPacketBufferSize()) + " (" + ssls.getPacketBufferSize() + ")");
}
Example 87
Project: jwebsocket-master File: NettyEnginePipeLineFactory.java View source code |
/**
* {@inheritDoc}
* <p/>
* NOTE: initially when the server is started <tt>HTTP</tt> encoder/decoder
* are added in the channel pipeline which is required for the initial
* handshake request for WebSocket connection. Once the connection is made
* by sending the appropriate response the encoder/decoder is replaced at
* runtime by {@code WebSocketFrameDecoder} and {@code
* WebSocketFrameEncoder}.
*/
@Override
public ChannelPipeline getPipeline() throws Exception {
// Create a default pipeline implementation.
ChannelPipeline pipeline = Channels.pipeline();
// Add SSL handler first to encrypt and decrypt everything.
if (sslEnabled) {
SSLEngine sslEngine = JWebSocketSslContextFactory.getServerContext().createSSLEngine();
sslEngine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(sslEngine));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
pipeline.addLast("encoder", new HttpResponseEncoder());
// create a new handler instance for each new channel to avoid a
// race condition where a unauthenticated client can get the
// confidential information:
pipeline.addLast("handler", new NettyEngineHandler(engine));
return pipeline;
}
Example 88
Project: kafka-master File: SslFactoryTest.java View source code |
@Test
public void testSslFactoryConfiguration() throws Exception {
File trustStoreFile = File.createTempFile("truststore", ".jks");
Map<String, Object> serverSslConfig = TestSslUtils.createSslConfig(false, true, Mode.SERVER, trustStoreFile, "server");
SslFactory sslFactory = new SslFactory(Mode.SERVER);
sslFactory.configure(serverSslConfig);
//host and port are hints
SSLEngine engine = sslFactory.createSslEngine("localhost", 0);
assertNotNull(engine);
String[] expectedProtocols = { "TLSv1.2" };
assertArrayEquals(expectedProtocols, engine.getEnabledProtocols());
assertEquals(false, engine.getUseClientMode());
}
Example 89
Project: litesockets-master File: TCPServer.java View source code |
public void run() {
try {
final TCPClient client = getSocketExecuter().createTCPClient((SocketChannel) c);
if (sslCtx != null) {
SSLEngine ssle;
if (hostName == null) {
ssle = sslCtx.createSSLEngine(client.getLocalSocketAddress().getHostName(), client.getLocalSocketAddress().getPort());
} else {
ssle = sslCtx.createSSLEngine(hostName, client.getLocalSocketAddress().getPort());
}
ssle.setUseClientMode(false);
client.setSSLEngine(ssle);
if (doHandshake) {
client.startSSL();
}
}
if (getClientAcceptor() != null) {
getClientAcceptor().accept(client);
}
} catch (IOException e) {
}
}
Example 90
Project: load-balancer-master File: TestHttpServerPipelineFactory.java View source code |
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = pipeline();
if (!terminateTLSTraffic) {
SslConfiguration sslConfig = new SslConfiguration();
sslConfig.setKeyStorePath(TestHttpServerPipelineFactory.class.getClassLoader().getResource("keystore").getFile());
sslConfig.setKeyStorePassword("123456");
sslConfig.setTrustStorePath(TestHttpServerPipelineFactory.class.getClassLoader().getResource("keystore").getFile());
sslConfig.setTrustStorePassword("123456");
SslContextFactory factory = new SslContextFactory(sslConfig);
SSLEngine sslEngine = factory.newSslEngine();
sslEngine.setUseClientMode(false);
pipeline.addLast("ssl", new SslHandler(sslEngine));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
// http://code.google.com/p/commscale/issues/detail?id=5 support for HttpChunks
// https://telestax.atlassian.net/browse/LB-8 if commented accessing the RestComm Management console fails, so making the maxContentLength Configurable
pipeline.addLast("aggregator", new HttpChunkAggregator(maxContentLength));
pipeline.addLast("encoder", new HttpResponseEncoder());
// Remove the following line if you don't want automatic content compression.
//pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addLast("handler", new HttpServerRequestHandler(requestCount, requests, chunkResponse, badSever));
return pipeline;
}
Example 91
Project: neo4j-java-driver-master File: TLSSocketChannelWriteFragmentationIT.java View source code |
@Override
protected void testForBufferSizes(byte[] blobOfData, int networkFrameSize, int userBufferSize) throws Exception {
SSLEngine engine = sslCtx.createSSLEngine();
engine.setUseClientMode(true);
SocketAddress address = new InetSocketAddress(serverSocket.getInetAddress(), serverSocket.getLocalPort());
ByteChannel ch = new LittleAtATimeChannel(SocketChannel.open(address), networkFrameSize);
try (TLSSocketChannel channel = TLSSocketChannel.create(ch, DEV_NULL_LOGGER, engine)) {
ByteBuffer writeBuffer = ByteBuffer.wrap(blobOfData);
while (writeBuffer.position() < writeBuffer.capacity()) {
writeBuffer.limit(Math.min(writeBuffer.capacity(), writeBuffer.position() + userBufferSize));
int remainingBytes = writeBuffer.remaining();
assertEquals(remainingBytes, channel.write(writeBuffer));
}
}
}
Example 92
Project: netty-master File: SslContextBuilderTest.java View source code |
private static void testClientContextFromFile(SslProvider provider) throws Exception {
SelfSignedCertificate cert = new SelfSignedCertificate();
SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(provider).keyManager(cert.certificate(), cert.privateKey()).trustManager(cert.certificate()).clientAuth(ClientAuth.OPTIONAL);
SslContext context = builder.build();
SSLEngine engine = context.newEngine(UnpooledByteBufAllocator.DEFAULT);
assertFalse(engine.getWantClientAuth());
assertFalse(engine.getNeedClientAuth());
engine.closeInbound();
engine.closeOutbound();
}
Example 93
Project: nettybook2-master File: SecureChatServerInitializer.java View source code |
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// Add SSL handler first to encrypt and decrypt everything.
// In this example, we use a bogus certificate in the server side
// and accept any invalid certificates in the client side.
// You will need something more complicated to identify both
// and server in the real world.
//
// Read SecureChatSslContextFactory
// if you need client certificate authentication.
SSLEngine engine = null;
if (SSLMODE.CA.toString().equals(tlsMode)) {
engine = SecureChatSslContextFactory.getServerContext(tlsMode, System.getProperty("user.dir") + "/src/com/phei/netty/ssl/conf/client/sChat.jks", null).createSSLEngine();
} else if (SSLMODE.CSA.toString().equals(tlsMode)) {
engine = SecureChatSslContextFactory.getServerContext(tlsMode, System.getProperty("user.dir") + "/src/com/phei/netty/ssl/conf/twoway/sChat.jks", System.getProperty("user.dir") + "/src/com/phei/netty/ssl/conf/twoway/sChat.jks").createSSLEngine();
// engine = SecureChatSslContextFactory
// .getServerContext(
// tlsMode,
// System.getProperty("user.dir")
// + "/src/com/phei/netty/ssl/conf/client/sChat.jks",
// System.getProperty("user.dir")
// + "/src/com/phei/netty/ssl/conf/client/sChat.jks")
// .createSSLEngine();
} else {
System.err.println("ERROR : " + tlsMode);
System.exit(-1);
}
engine.setUseClientMode(false);
// Client auth
if (SSLMODE.CSA.toString().equals(tlsMode))
engine.setNeedClientAuth(true);
pipeline.addLast("ssl", new SslHandler(engine));
// On top of the SSL handler, add the text line codec.
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder());
pipeline.addLast("encoder", new StringEncoder());
// and then business logic.
pipeline.addLast("handler", new SecureChatServerHandler());
}
Example 94
Project: onos-master File: OpenflowPipelineFactory.java View source code |
@Override
public ChannelPipeline getPipeline() throws Exception {
OFChannelHandler handler = new OFChannelHandler(controller);
ChannelPipeline pipeline = Channels.pipeline();
if (sslContext != null) {
log.debug("OpenFlow SSL enabled.");
SSLEngine sslEngine = sslContext.createSSLEngine();
sslEngine.setNeedClientAuth(true);
sslEngine.setUseClientMode(false);
sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
sslEngine.setEnableSessionCreation(true);
SslHandler sslHandler = new SslHandler(sslEngine);
pipeline.addLast("ssl", sslHandler);
} else {
log.debug("OpenFlow SSL disabled.");
}
pipeline.addLast("ofmessagedecoder", new OFMessageDecoder());
pipeline.addLast("ofmessageencoder", new OFMessageEncoder());
pipeline.addLast("idle", idleHandler);
pipeline.addLast("timeout", readTimeoutHandler);
// XXX S ONOS: was 15 increased it to fix Issue #296
pipeline.addLast("handshaketimeout", new HandshakeTimeoutHandler(handler, timer, 60));
if (pipelineExecutor != null) {
pipeline.addLast("pipelineExecutor", new ExecutionHandler(pipelineExecutor));
}
pipeline.addLast("handler", handler);
return pipeline;
}
Example 95
Project: rabbitmq-java-client-master File: SocketChannelFrameHandlerFactory.java View source code |
@Override
public FrameHandler create(Address addr) throws IOException {
int portNumber = ConnectionFactory.portOrDefault(addr.getPort(), ssl);
SSLEngine sslEngine = null;
SocketChannel channel = null;
try {
if (ssl) {
sslEngine = sslContext.createSSLEngine(addr.getHost(), portNumber);
sslEngine.setUseClientMode(true);
}
SocketAddress address = new InetSocketAddress(addr.getHost(), portNumber);
channel = SocketChannel.open();
channel.configureBlocking(true);
if (nioParams.getSocketChannelConfigurator() != null) {
nioParams.getSocketChannelConfigurator().configure(channel);
}
channel.connect(address);
if (ssl) {
sslEngine.beginHandshake();
boolean handshake = SslEngineHelper.doHandshake(channel, sslEngine);
if (!handshake) {
throw new SSLException("TLS handshake failed");
}
}
channel.configureBlocking(false);
// lock
stateLock.lock();
NioLoopContext nioLoopContext = null;
try {
long modulo = globalConnectionCount.getAndIncrement() % nioParams.getNbIoThreads();
nioLoopContext = nioLoopContexts.get((int) modulo);
nioLoopContext.initStateIfNecessary();
SocketChannelFrameHandlerState state = new SocketChannelFrameHandlerState(channel, nioLoopContext, nioParams, sslEngine);
state.startReading();
SocketChannelFrameHandler frameHandler = new SocketChannelFrameHandler(state);
return frameHandler;
} finally {
stateLock.unlock();
}
} catch (IOException e) {
try {
if (sslEngine != null && channel != null) {
SslEngineHelper.close(channel, sslEngine);
}
channel.close();
} catch (IOException closingException) {
}
throw e;
}
}
Example 96
Project: restlet-framework-java-master File: WrapperSslContextSpi.java View source code |
/**
* Initializes the SSL engine with additional parameters from the SSL
* context factory.
*
* @param sslEngine
* The SSL engine to initialize.
*/
protected void initEngine(SSLEngine sslEngine) {
if (getContextFactory().isNeedClientAuthentication()) {
sslEngine.setNeedClientAuth(true);
} else if (getContextFactory().isWantClientAuthentication()) {
sslEngine.setWantClientAuth(true);
}
if ((getContextFactory().getEnabledCipherSuites() != null) || (getContextFactory().getDisabledCipherSuites() != null)) {
sslEngine.setEnabledCipherSuites(getContextFactory().getSelectedCipherSuites(sslEngine.getSupportedCipherSuites()));
}
if ((getContextFactory().getEnabledProtocols() != null) || (getContextFactory().getDisabledProtocols() != null)) {
sslEngine.setEnabledProtocols(getContextFactory().getSelectedSslProtocols(sslEngine.getSupportedProtocols()));
}
}
Example 97
Project: RxNetty-master File: SecureDefaultHttpClient.java View source code |
public static void main(String[] args) { ExamplesEnvironment env = ExamplesEnvironment.newEnvironment(SecureDefaultHttpClient.class); Logger logger = env.getLogger(); SSLEngine sslEngine = null; try { sslEngine = defaultSSLEngineForClient(); } catch (NoSuchAlgorithmException nsae) { logger.error("Failed to create SSLEngine.", nsae); System.exit(-1); } HttpClient.newClient(HOST, PORT).enableWireLogging("http-secure-default-client", LogLevel.DEBUG).secure(sslEngine).createGet("/").doOnNext( resp -> logger.info(resp.toString())).flatMap( resp -> { System.out.println(resp.getStatus()); return resp.getContent().map( bb -> bb.toString(Charset.defaultCharset())); }).toBlocking().forEach(logger::info); }
Example 98
Project: SecureNIO-master File: SSLSecurityTest.java View source code |
public static void main(String[] args) throws Exception {
//System.err.println("Creating SSL context");
char[] passphrase = "alpharesearch".toCharArray();
KeyStore ks = KeyStore.getInstance("JKS");
//ks.load(new FileInputStream("test.jks"), passphrase);
ks.load(new FileInputStream("keystore.jks"), passphrase);
//System.err.println("Loaded keystore");
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(ks);
//System.err.println("Initialized trustManagerFactory");
context.init(null, tmf.getTrustManagers(), null);
SSLEngine engine = context.createSSLEngine();
engine.setUseClientMode(false);
engine.setEnabledProtocols(new String[] { "SSLv3", "TLSv1.2" });
String[] protocols = engine.getEnabledProtocols();
System.out.println("===========PROTOCOLS=========");
for (int i = 0; i < protocols.length; i++) {
System.out.println(protocols[i]);
}
engine.setEnabledCipherSuites(new String[] { "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256", "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA", "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA" });
String[] suites = engine.getEnabledCipherSuites();
System.out.println("=============SUITES===========");
for (int i = 0; i < suites.length; i++) {
System.out.println(suites[i]);
}
}
Example 99
Project: smscgateway-master File: TestSmppClient.java View source code |
protected DefaultSmppSession createSession(Channel channel, SmppSessionConfiguration config, SmppSessionHandler sessionHandler) throws SmppTimeoutException, SmppChannelException, InterruptedException {
TestSmppSession session = new TestSmppSession(SmppSession.Type.CLIENT, config, channel, sessionHandler, monitorExecutor);
// add SSL handler
if (config.isUseSsl()) {
SslConfiguration sslConfig = config.getSslConfiguration();
if (sslConfig == null)
throw new IllegalStateException("sslConfiguration must be set");
try {
SslContextFactory factory = new SslContextFactory(sslConfig);
SSLEngine sslEngine = factory.newSslEngine();
sslEngine.setUseClientMode(true);
channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_SSL_NAME, new SslHandler(sslEngine));
} catch (Exception e) {
throw new SmppChannelConnectException("Unable to create SSL session]: " + e.getMessage(), e);
}
}
// add the thread renamer portion to the pipeline
if (config.getName() != null) {
channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_THREAD_RENAMER_NAME, new SmppSessionThreadRenamer(config.getName()));
} else {
// logger.warn("Session configuration did not have a name set - skipping threadRenamer in pipeline");
}
// create the logging handler (for bytes sent/received on wire)
SmppSessionLogger loggingHandler = new SmppSessionLogger(DefaultSmppSession.class.getCanonicalName(), config.getLoggingOptions());
channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_LOGGER_NAME, loggingHandler);
// add a writeTimeout handler after the logger
if (config.getWriteTimeout() > 0) {
WriteTimeoutHandler writeTimeoutHandler = new WriteTimeoutHandler(new org.jboss.netty.util.HashedWheelTimer(), /* writeTimeoutTimer */
config.getWriteTimeout(), TimeUnit.MILLISECONDS);
channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_WRITE_TIMEOUT_NAME, writeTimeoutHandler);
}
// add a new instance of a decoder (that takes care of handling frames)
channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_PDU_DECODER_NAME, new SmppSessionPduDecoder(session.getTranscoder()));
// create a new wrapper around a session to pass the pdu up the chain
channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_WRAPPER_NAME, new SmppSessionWrapper(session));
return session;
}
Example 100
Project: tomcat60-master File: Jre8Compat.java View source code |
@Override
public void setUseServerCipherSuitesOrder(SSLEngine engine, boolean useCipherSuitesOrder) {
try {
Object sslParameters = getSSLParametersEngineMethod.invoke(engine);
setUseCipherSuitesOrderMethod.invoke(sslParameters, Boolean.valueOf(useCipherSuitesOrder));
setSSLParametersEngineMethod.invoke(engine, sslParameters);
} catch (IllegalArgumentException e) {
throw new UnsupportedOperationException(e);
} catch (IllegalAccessException e) {
throw new UnsupportedOperationException(e);
} catch (InvocationTargetException e) {
throw new UnsupportedOperationException(e);
}
}
Example 101
Project: undertow-master File: JDK9AlpnProvider.java View source code |
@Override
public JDK9ALPNMethods run() {
try {
Method setApplicationProtocols = SSLParameters.class.getMethod("setApplicationProtocols", String[].class);
Method getApplicationProtocol = SSLEngine.class.getMethod("getApplicationProtocol");
UndertowLogger.ROOT_LOGGER.debug("Using JDK9 ALPN");
return new JDK9ALPNMethods(setApplicationProtocols, getApplicationProtocol);
} catch (Exception e) {
UndertowLogger.ROOT_LOGGER.debug("JDK9 ALPN not supported", e);
return null;
}
}