Java Examples for javax.net.ssl.SSLException
The following java examples will help you to understand the usage of javax.net.ssl.SSLException. These source code samples are taken from different open source projects.
Example 1
| Project: jacorb-master File: SSLListenerUtil.java View source code |
/**
* <code>processException</code> examines the supplied exception for an
* SSLException and can notify a listener.
*
* @param ex an <code>IOException</code> value
*/
public static void processException(ORB orb, IIOPConnection iiop, Socket socket, IOException ex) {
final SSLSessionListener listener = orb.getTransportManager().getSocketFactoryManager().getSSLListener();
// TODO kategorie
final Logger logger = orb.getConfiguration().getLogger("org.jacorb.ssl.sessionlistener");
String localhost = IIOPAddress.getLocalHostAddress(logger);
// to call the correct listener.
if (ex instanceof SSLHandshakeException) {
listener.handshakeException(new SSLSessionEvent(iiop, socket.getInetAddress().getHostAddress(), socket.getPort(), null, socket.getLocalPort(), localhost, ex));
} else if (ex instanceof SSLKeyException) {
listener.keyException(new SSLSessionEvent(iiop, socket.getInetAddress().getHostAddress(), socket.getPort(), null, socket.getLocalPort(), localhost, ex));
} else if (ex instanceof SSLPeerUnverifiedException) {
listener.peerUnverifiedException(new SSLSessionEvent(iiop, socket.getInetAddress().getHostAddress(), socket.getPort(), null, socket.getLocalPort(), localhost, ex));
} else if (ex instanceof SSLProtocolException) {
listener.protocolException(new SSLSessionEvent(iiop, socket.getInetAddress().getHostAddress(), socket.getPort(), null, socket.getLocalPort(), localhost, ex));
} else if (ex instanceof SSLException) {
listener.sslException(new SSLSessionEvent(iiop, socket.getInetAddress().getHostAddress(), socket.getPort(), null, socket.getLocalPort(), localhost, ex));
} else {
if (logger.isDebugEnabled()) {
logger.debug("Unknown exception type " + ex.getClass().getName() + " with exception " + ex);
}
}
}Example 2
| Project: ssl_npn-master File: SSLEngineHandshaker.java View source code |
public static void negotiateHandshake(SSLEngineImpl engine, SocketChannel socket) throws SSLException, IOException {
SSLSession session = engine.getSession();
ByteBuffer myAppData = ByteBuffer.allocate(session.getApplicationBufferSize());
ByteBuffer myNetData = ByteBuffer.allocate(session.getPacketBufferSize());
ByteBuffer peerAppData = ByteBuffer.allocate(session.getApplicationBufferSize());
ByteBuffer peerNetData = ByteBuffer.allocate(session.getPacketBufferSize());
engine.beginHandshake();
while (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
switch(engine.getHandshakeStatus()) {
case NEED_TASK:
engine.getDelegatedTask().run();
break;
case NEED_WRAP:
SSLEngineResult result = engine.wrap(myAppData, myNetData);
socket.configureBlocking(true);
myNetData.flip();
socket.write(myNetData);
myNetData.compact();
break;
case NEED_UNWRAP:
socket.configureBlocking(false);
socket.read(peerNetData);
peerNetData.flip();
result = engine.unwrap(peerNetData, peerAppData);
peerAppData.rewind();
peerNetData.compact();
break;
}
}
}Example 3
| Project: audit-master File: MainActivity_Scheme.java View source code |
private void https() {
DefaultHttpClient client = new DefaultHttpClient();
try {
KeyStore ks = KeyStoreUtil.getEmptyKeyStore();
// 验��有密钥
KeyStoreUtil.loadX509Certificate(ks, getBaseContext().getResources().getAssets().open("cacert.crt"));
Scheme sch = new Scheme("https", new SSLSocketFactoryEx(ks), 443);
client.getConnectionManager().getSchemeRegistry().register(sch);
String urlString = "https://mail.qq.com/cgi-bin/loginpage";
HttpGet request = new HttpGet(urlString);
Log.e("testcaseLog_urlString", urlString);
HttpResponse response = client.execute(request);
checkResponse(response);
String result_json = EntityUtils.toString(response.getEntity(), "UTF-8");
Log.e("testcaseLog_result", result_json);
} catch (SSLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
}Example 4
| Project: FireFly-master File: SelfSignedCertificateOpenSSLContextFactory.java View source code |
@Override
public SslContext createSSLContext(boolean clientMode) {
SslContextBuilder sslContextBuilder = clientMode ? SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) : SslContextBuilder.forServer(selfSignedCertificate.certificate(), selfSignedCertificate.privateKey());
try {
return sslContextBuilder.ciphers(SecurityUtils.CIPHERS, SupportedCipherSuiteFilter.INSTANCE).applicationProtocolConfig(new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, ApplicationProtocolConfig.SelectedListenerFailureBehavior.CHOOSE_MY_LAST_PROTOCOL, supportedProtocols)).build();
} catch (SSLException e) {
log.error("create ssl context exception", e);
throw new CommonRuntimeException(e);
}
}Example 5
| Project: glaze-http-master File: TestRetry.java View source code |
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
this.retries = executionCount;
if (executionCount >= 2) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectException) {
// Connection refused
return true;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}Example 6
| Project: jetty.project-master File: JDK9ServerALPNProcessor.java View source code |
private String process(SSLEngine sslEngine, List<String> protocols) {
try {
if (LOG.isDebugEnabled())
LOG.debug("ALPN selecting among client{}", protocols);
ALPN.ServerProvider provider = (ALPN.ServerProvider) ALPN.remove(sslEngine);
return provider == null ? "" : provider.select(protocols);
} catch (SSLException x) {
return null;
}
}Example 7
| Project: mockserver-master File: HttpClientInitializer.java View source code |
@Override
public void initChannel(SocketChannel channel) throws SSLException {
ChannelPipeline pipeline = channel.pipeline();
if (secure) {
pipeline.addLast(new SslHandler(SSLFactory.createClientSSLEngine()));
}
// add logging
if (logger.isDebugEnabled()) {
pipeline.addLast(new LoggingHandler(this.getClass().getSimpleName() + " -->"));
}
pipeline.addLast(new HttpClientCodec());
pipeline.addLast(new HttpContentDecompressor());
pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
pipeline.addLast(new MockServerClientCodec());
pipeline.addLast(httpClientHandler);
}Example 8
| Project: MUtils-master File: NetExceptionUtil.java View source code |
protected static int resOf(Exception e) {
if (e instanceof NoConnectionException || e instanceof ConnectException) {
return R.string.exception_no_connection;
}
if (e instanceof ConnectTimeoutException || e instanceof SocketException || e instanceof SocketTimeoutException) {
return R.string.exception_timeout;
}
if (e instanceof NoHttpResponseException || e instanceof FileNotFoundException || e instanceof EOFException || e instanceof UnknownHostException || e instanceof SSLException) {
return R.string.exception_no_response;
}
if (e instanceof HttpStatusException) {
return R.string.exception_http_status;
}
if (e instanceof ErrorCodeException) {
try {
String name = "exception_" + ((ErrorCodeException) e).getCode();
return R.string.class.getField(name).getInt(null);
} catch (Exception ex) {
return 0;
}
}
return 0;
}Example 9
| Project: netty-master File: Http2Server.java View source code |
private static SslContext configureTLS() throws CertificateException, SSLException {
SelfSignedCertificate ssc = new SelfSignedCertificate();
ApplicationProtocolConfig apn = new ApplicationProtocolConfig(Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1);
return SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey(), null).ciphers(CIPHERS, SupportedCipherSuiteFilter.INSTANCE).applicationProtocolConfig(apn).build();
}Example 10
| 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 11
| Project: RestComm-master File: SslPlayHandler.java View source code |
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
// Redirect to the root as we don't know the url at that point
if (e.getCause() instanceof SSLException) {
Logger.debug(e.getCause(), "");
InetSocketAddress inet = ((InetSocketAddress) ctx.getAttachment());
ctx.getPipeline().remove("ssl");
HttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
nettyResponse.setHeader(LOCATION, "https://" + inet.getHostName() + ":" + Server.httpsPort + "/");
ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
writeFuture.addListener(ChannelFutureListener.CLOSE);
} else {
Logger.error(e.getCause(), "");
e.getChannel().close();
}
}Example 12
| Project: restcommander-master File: SslPlayHandler.java View source code |
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
// Redirect to the root as we don't know the url at that point
if (e.getCause() instanceof SSLException) {
Logger.debug(e.getCause(), "");
InetSocketAddress inet = ((InetSocketAddress) ctx.getAttachment());
ctx.getPipeline().remove("ssl");
HttpResponse nettyResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.TEMPORARY_REDIRECT);
nettyResponse.setHeader(LOCATION, "https://" + inet.getHostName() + ":" + Server.httpsPort + "/");
ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
writeFuture.addListener(ChannelFutureListener.CLOSE);
} else {
Logger.error(e.getCause(), "");
e.getChannel().close();
}
}Example 13
| Project: undertow-master File: ALPNHackServerByteArrayOutputStream.java View source code |
@Override
public void write(byte[] b, int off, int len) {
if (ready) {
if (b[off] == 2) {
// server hello
//we are done processing
ready = false;
//TODO: actual ALPN
serverHello = new byte[len];
System.arraycopy(b, off, serverHello, 0, len);
try {
serverHello = ALPNHackServerHelloExplorer.addAlpnExtensionsToServerHello(serverHello, alpnProtocol);
} catch (SSLException e) {
throw new RuntimeException(e);
}
ALPNHackSSLEngine.regenerateHashes(sslEngine, this, toByteArray(), serverHello);
return;
}
}
super.write(b, off, len);
}Example 14
| Project: blynk-server-master File: SslUtil.java View source code |
public static SslContext build(File serverCert, File serverKey, String serverPass, SslProvider sslProvider, File clientCert) throws SSLException {
log.info("Creating SSL context for cert '{}', key '{}', key pass '{}'", serverCert.getAbsolutePath(), serverKey.getAbsoluteFile(), serverPass);
if (serverPass == null || serverPass.isEmpty()) {
return SslContextBuilder.forServer(serverCert, serverKey).sslProvider(sslProvider).trustManager(clientCert).build();
} else {
return SslContextBuilder.forServer(serverCert, serverKey, serverPass).sslProvider(sslProvider).trustManager(clientCert).build();
}
}Example 15
| Project: buddycloud-android-master File: TLSSNISocketFactory.java View source code |
// TLS layer
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(s, host, port, autoClose);
// set SNI before the handshake
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Logger.info(TAG, "Setting SNI hostname");
sslSocketFactory.setHostname(ssl, host);
} else {
Logger.warn(TAG, "No SNI support below Android 4.2!");
}
// now do the TLS handshake
ssl.startHandshake();
SSLSession session = ssl.getSession();
if (session == null)
throw new SSLException("Cannot verify SSL socket without session");
// verify host name (important!)
if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(host, session))
throw new SSLPeerUnverifiedException("Cannot verify hostname: " + host);
return ssl;
}Example 16
| Project: camel-master File: SplunkEndpoint.java View source code |
public synchronized boolean reset(Exception e) {
boolean answer = false;
if ((e instanceof RuntimeException && ((RuntimeException) e).getCause() instanceof ConnectException) || ((e instanceof SocketException) || (e instanceof SSLException))) {
LOG.warn("Got exception from Splunk. Service will be reset.");
this.service = null;
answer = true;
}
return answer;
}Example 17
| Project: DavidWebb-master File: RetryManager.java View source code |
/**
* Analyzes whether the cause of an exception is worth retrying the request.
* <br>
* This is not covering all situations and in case of doubt the exception is considered not
* recoverable. @YOU: if you find a case where an exception is recoverable, create an issue!
* @param webbException the exception to analyze
* @return <tt>true</tt> if it makes sense for the request to be retried again.
*/
public boolean isRecoverable(WebbException webbException) {
Throwable cause = webbException.getCause();
if (cause == null) {
return false;
}
if (cause instanceof SSLException) {
SSLException sslException = (SSLException) cause;
if (sslException.toString().toLowerCase().contains("connection reset by peer")) {
return true;
}
}
if (cause instanceof SocketTimeoutException) {
return true;
}
return false;
}Example 18
| Project: ddf-master File: SolrHttpRequestRetryHandler.java View source code |
@Override
public boolean retryRequest(IOException e, int retryCount, HttpContext httpContext) {
if (e instanceof InterruptedIOException) {
LOGGER.debug("Connection timeout.");
}
if (e instanceof UnknownHostException) {
LOGGER.warn("Solr Client: Unknown host.");
}
if (e instanceof SSLException) {
LOGGER.warn("Solr Client: SSL handshake exception.");
}
LOGGER.debug("Connection failed", e);
try {
long waitTime = (long) Math.pow(2, Math.min(retryCount, MAX_RETRY_COUNT)) * 50;
LOGGER.debug("Solr Client: Connection failed, waiting {} before retrying.", DurationFormatUtils.formatDurationWords(waitTime, true, true));
synchronized (this) {
wait(waitTime);
}
} catch (InterruptedException ie) {
LOGGER.debug("Exception while waiting.", ie);
}
return true;
}Example 19
| Project: deep-spark-master File: ExtractorServer.java View source code |
public static void start() throws CertificateException, SSLException, InterruptedException {
// Configure SSL.
final SslContext sslCtx;
if (SSL) {
SelfSignedCertificate ssc = new SelfSignedCertificate();
sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
} else {
sslCtx = null;
}
bossGroup = new NioEventLoopGroup(1);
workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ExtractorServerInitializer(sslCtx));
b.bind(PORT).sync().channel().closeFuture().sync();
}Example 20
| Project: dz-master File: SSLContextFactory.java View source code |
/**
* Create an SSL context object.
*
* @param protocol Secure protocol. Values that are known to work are:
* {@code SSLv3}, {@code TLS}.
* @param keyStoreName Keystore file name.
* @param password Keystore password.
* @return The SSL context.
* @throws SSLException If there was an SSL related problem.
*/
public static SSLContext createContext(String protocol, String keyStoreName, String password) throws SSLException {
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
SSLContext ctx = SSLContext.getInstance(protocol);
if (password == null) {
// Whatever...
password = "";
}
char[] passwordArray = new char[password.length()];
for (int idx = 0; idx < password.length(); idx++) {
passwordArray[idx] = password.charAt(idx);
}
FileInputStream keyStoreFile = new FileInputStream(keyStoreName);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(keyStoreFile, null);
String keyManagementAlgorithm = "SunX509";
KeyManagerFactory km = KeyManagerFactory.getInstance(keyManagementAlgorithm);
km.init(ks, passwordArray);
KeyManager[] keyManagerSet = km.getKeyManagers();
for (int i = 0; i < keyManagerSet.length; i++) {
// System.err.println("KeyManager " + keyManagerSet[i]);
}
TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(keyManagementAlgorithm);
tmFactory.init(ks);
TrustManager[] trustManagerSet = tmFactory.getTrustManagers();
for (int i = 0; i < trustManagerSet.length; i++) {
// System.err.println("TrustManager " + trustManagerSet[i]);
}
ctx.init(keyManagerSet, trustManagerSet, random);
return ctx;
} catch (Throwable t) {
SSLException ex = new SSLException("Can't create secure connection (SSLContext)");
ex.initCause(t);
throw ex;
}
}Example 21
| Project: Glowstone-master File: HttpClient.java View source code |
public static void connect(String url, EventLoop eventLoop, HttpCallback callback) {
URI uri = URI.create(url);
String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
int port = uri.getPort();
SslContext sslCtx = null;
if ("https".equalsIgnoreCase(scheme)) {
if (port == -1)
port = 443;
try {
sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} catch (SSLException e) {
callback.error(e);
return;
}
} else if ("http".equalsIgnoreCase(scheme)) {
if (port == -1)
port = 80;
} else {
throw new IllegalArgumentException("Only http(s) is supported!");
}
new Bootstrap().group(eventLoop).resolver(resolverGroup).channel(Epoll.isAvailable() ? EpollSocketChannel.class : NioSocketChannel.class).handler(new HttpChannelInitializer(sslCtx, callback)).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000).connect(InetSocketAddress.createUnresolved(host, port)).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
String path = uri.getRawPath() + (uri.getRawQuery() == null ? "" : "?" + uri.getRawQuery());
HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, path);
request.headers().set(HttpHeaderNames.HOST, host);
future.channel().writeAndFlush(request);
} else {
callback.error(future.cause());
}
});
}Example 22
| Project: http2-netty-master File: Http2Server.java View source code |
private SslContext configureTLS() throws CertificateException, SSLException {
SelfSignedCertificate ssc = new SelfSignedCertificate();
final SslContext sslCtx = SslContext.newServerContext(SslProvider.JDK, ssc.certificate(), ssc.privateKey(), null, Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE, new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.FATAL_ALERT, SelectedListenerFailureBehavior.FATAL_ALERT, SelectedProtocol.HTTP_2.protocolName(), SelectedProtocol.HTTP_1_1.protocolName()), 0, 0);
return sslCtx;
}Example 23
| Project: netty-storm-master File: NettyProducer.java View source code |
static void connect() {
EventLoopGroup group = new NioEventLoopGroup();
try {
// Configure SSL.
//TODO Change the insecure Trust Manager Factory for a chain of trusted certificates...
final SslContext sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new NettyConnectionInitializer(sslCtx, host, port));
Channel channel = bootstrap.connect(host, port).sync().channel();
NettyChannelSpecification nettyChannel = new NettyChannelSpecification(channel);
//Simple JSONObject to ilustrate the example
JSONObject objToSend = new JSONObject();
objToSend.put("topic", "I Am Alive");
while (true) {
if (!channel.isActive()) {
throw new java.nio.channels.ClosedChannelException();
}
//Keep sending the JSON Object until the channel drops...
System.out.println("[Netty Producer] Sent to network: " + objToSend.toString());
nettyChannel.send(objToSend);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.err.println("[Netty Producer] Producer Interrupted, restarting the producer.");
restart(group);
} catch (SSLException e) {
System.err.println("[Netty Producer] Restarting because it wasn't possible to establish a safe connection with the server :(");
restart(group);
} catch (ClosedChannelException e) {
System.err.println("[Netty Producer] The channel has dropped...");
restart(group);
} catch (Exception e) {
System.err.println(e.getMessage());
restart(group);
}
}Example 24
| Project: netty.book.kor-master File: HttpSnoopServer.java View source code |
public static void main(String[] args) throws Exception {
SslContext sslCtx = null;
try {
File certChainFile = new File("netty.crt");
File keyFile = new File("privatekey.pem");
keyFile.exists();
sslCtx = SslContext.newServerContext(certChainFile, keyFile, "1234");
} catch (SSLException e) {
e.printStackTrace();
System.out.println("Can not create SSL context! \n Server will be stop!");
}
// Configure the server.
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpSnoopServerInitializer(sslCtx));
Channel ch = b.bind(PORT).sync().channel();
ch.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}Example 25
| 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 26
| Project: Overchan-Android-master File: HttpRequestException.java View source code |
public static String getMessage(Exception e) {
if (e instanceof SSLException)
return getString(R.string.error_ssl, "SSL/HTTPS Error");
if (e instanceof SocketTimeoutException)
return getString(R.string.error_connection_timeout, "Connection timed out");
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1 && e instanceof UnknownHostException)
return "Unable to resolve host";
if (e != null && e.getMessage() != null)
return e.getLocalizedMessage();
return getString(R.string.error_connection, "Unable to connect to server");
}Example 27
| Project: oxAuth-master File: Utils.java View source code |
public static HttpClient createHttpClientTrustAll() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}, new X509HostnameVerifier() {
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
registry.register(new Scheme("https", 443, sf));
ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
return new DefaultHttpClient(ccm);
}Example 28
| 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 29
| Project: uma-master File: Utils.java View source code |
public static HttpClient createHttpClientTrustAll() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}, new X509HostnameVerifier() {
@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}
@Override
public void verify(String host, X509Certificate cert) throws SSLException {
}
@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
registry.register(new Scheme("https", 443, sf));
ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
return new DefaultHttpClient(ccm);
}Example 30
| Project: WaarpExec-master File: LocalExecSslClientHandler.java View source code |
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.warn("Unexpected exception from Outband while get information: " + firstMessage, cause);
if (firstMessage) {
firstMessage = false;
result.set(LocalExecDefaultResult.BadTransmition);
result.setException((Exception) cause);
back = new StringBuilder("Error in LocalExec: ").append(result.getException().getMessage()).append('\n');
} else {
if (cause instanceof SSLException) {
// ignore ?
logger.warn("Ignore exception ?", cause);
return;
}
back.append("\nERROR while receiving answer: ");
result.setException((Exception) cause);
back.append(result.getException().getMessage()).append('\n');
}
actionBeforeClose(ctx.channel());
WaarpSslUtility.closingSslChannel(ctx.channel());
}Example 31
| 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 32
| Project: XPagesToolkit-master File: ClientSSLResistanceExtender.java View source code |
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLSv1");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
X509HostnameVerifier verifier = new X509HostnameVerifier() {
public void verify(String arg0, SSLSocket arg1) throws IOException {
}
public void verify(String arg0, X509Certificate arg1) throws SSLException {
}
public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException {
}
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}Example 33
| Project: Android-tcp-long-connection-based-on-Apache-mina-master File: SslHandler.java View source code |
/**
* Initialize the SSL handshake.
*
* @throws javax.net.ssl.SSLException If the underlying SSLEngine handshake initialization failed
*/
/* no qualifier */
void init() throws SSLException {
if (sslEngine != null) {
// We already have a SSL engine created, no need to create a new one
return;
}
LOGGER.debug("{} Initializing the SSL Handler", sslFilter.getSessionInfo(session));
InetSocketAddress peer = (InetSocketAddress) session.getAttribute(SslFilter.PEER_ADDRESS);
// Create the SSL engine here
if (peer == null) {
sslEngine = sslFilter.sslContext.createSSLEngine();
} else {
sslEngine = sslFilter.sslContext.createSSLEngine(peer.getHostName(), peer.getPort());
}
// Initialize the engine in client mode if necessary
sslEngine.setUseClientMode(sslFilter.isUseClientMode());
// Initialize the different SslEngine modes
if (!sslEngine.getUseClientMode()) {
// Those parameters are only valid when in server mode
if (sslFilter.isWantClientAuth()) {
sslEngine.setWantClientAuth(true);
}
if (sslFilter.isNeedClientAuth()) {
sslEngine.setNeedClientAuth(true);
}
}
// Set the cipher suite to use by this SslEngine instance
if (sslFilter.getEnabledCipherSuites() != null) {
sslEngine.setEnabledCipherSuites(sslFilter.getEnabledCipherSuites());
}
// Set the list of enabled protocols
if (sslFilter.getEnabledProtocols() != null) {
sslEngine.setEnabledProtocols(sslFilter.getEnabledProtocols());
}
// TODO : we may not need to call this method...
// However, if we don't call it here, the tests are failing. Why?
sslEngine.beginHandshake();
handshakeStatus = sslEngine.getHandshakeStatus();
// Default value
writingEncryptedData = false;
// We haven't yet started a SSL negotiation
// set the flags accordingly
firstSSLNegociation = true;
handshakeComplete = false;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("{} SSL Handler Initialization done.", sslFilter.getSessionInfo(session));
}
}Example 34
| Project: android-15-master File: SSLEngineAppData.java View source code |
/**
* Places the data from the buffer into the array of destination
* ByteBuffer objects.
*/
protected int placeTo(ByteBuffer[] dsts, int offset, int length) {
if (buffer == null) {
return 0;
}
int pos = 0;
int len = buffer.length;
int rem;
// write data to the buffers
for (int i = offset; i < offset + length; i++) {
rem = dsts[i].remaining();
// TODO: optimization work - use hasArray, array(), arraycopy
if (len - pos < rem) {
// can fully write remaining data into buffer
dsts[i].put(buffer, pos, len - pos);
pos = len;
// data was written, exit
break;
}
// write chunk of data
dsts[i].put(buffer, pos, rem);
pos += rem;
}
if (pos != len) {
// But if it so, we should allert about internal error.
throw new AlertException(AlertProtocol.INTERNAL_ERROR, new SSLException("The received application data could not be fully written" + "into the destination buffers"));
}
buffer = null;
return len;
}Example 35
| Project: android-libcore64-master File: SSLExceptionTest.java View source code |
/**
* Test for <code>SSLException(Throwable)</code> constructor
* Assertion: constructs SSLException when <code>cause</code> is not
* null
*/
public void testSSLException04() {
SSLException sE = new SSLException(tCause);
if (sE.getMessage() != null) {
String toS = tCause.toString();
String getM = sE.getMessage();
assertTrue("getMessage() should contain ".concat(toS), (getM.indexOf(toS) != -1));
}
assertNotNull("getCause() must not return null", sE.getCause());
assertEquals("getCause() must return ".concat(tCause.toString()), sE.getCause(), tCause);
}Example 36
| Project: android-network-discovery-master File: DownloadFile.java View source code |
private InputStream openURL(String url) {
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
try {
response = httpclient.execute(httpget);
} catch (SSLException e) {
Log.i(TAG, "SSL Certificate is not trusted");
response = httpclient.execute(httpget);
}
Log.i(TAG, "Status:[" + response.getStatusLine().toString() + "]");
HttpEntity entity = response.getEntity();
if (entity != null) {
return new GZIPInputStream(entity.getContent());
}
} catch (ClientProtocolException e) {
Log.e(TAG, "There was a protocol based error", e);
} catch (UnknownHostException e) {
Log.e(TAG, e.getMessage());
} catch (IOException e) {
Log.e(TAG, "There was an IO Stream related error", e);
}
return null;
}Example 37
| Project: android_libcore-master File: SSLEngineAppData.java View source code |
/**
* Places the data from the buffer into the array of destination
* ByteBuffer objects.
*/
protected int placeTo(ByteBuffer[] dsts, int offset, int length) {
if (buffer == null) {
return 0;
}
int pos = 0;
int len = buffer.length;
int rem;
// write data to the buffers
for (int i = offset; i < offset + length; i++) {
rem = dsts[i].remaining();
// TODO: optimization work - use hasArray, array(), arraycopy
if (len - pos < rem) {
// can fully write remaining data into buffer
dsts[i].put(buffer, pos, len - pos);
pos = len;
// data was written, exit
break;
}
// write chunk of data
dsts[i].put(buffer, pos, rem);
pos += rem;
}
if (pos != len) {
// But if it so, we should allert about internal error.
throw new AlertException(AlertProtocol.INTERNAL_ERROR, new SSLException("The received application data could not be fully written" + "into the destination buffers"));
}
buffer = null;
return len;
}Example 38
| Project: android_platform_libcore-master File: SSLExceptionTest.java View source code |
/**
* Test for <code>SSLException(Throwable)</code> constructor
* Assertion: constructs SSLException when <code>cause</code> is not
* null
*/
public void testSSLException04() {
SSLException sE = new SSLException(tCause);
if (sE.getMessage() != null) {
String toS = tCause.toString();
String getM = sE.getMessage();
assertTrue("getMessage() should contain ".concat(toS), (getM.indexOf(toS) != -1));
}
assertNotNull("getCause() must not return null", sE.getCause());
assertEquals("getCause() must return ".concat(tCause.toString()), sE.getCause(), tCause);
}Example 39
| Project: andstatus-master File: MisconfiguredSslHttpClientFactory.java View source code |
static HttpClient getHttpClient() {
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
// This is done to get rid of the "javax.net.ssl.SSLException: hostname in certificate didn't match" error
// See e.g. http://stackoverflow.com/questions/8839541/hostname-in-certificate-didnt-match
socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
schemeRegistry.register(new Scheme("https", socketFactory, 443));
HttpParams params = getHttpParams();
ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);
HttpClient client = new DefaultHttpClient(clientConnectionManager, params);
client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, MyPreferences.getConnectionTimeoutMs()).setIntParameter(CoreConnectionPNames.SO_TIMEOUT, MyPreferences.getConnectionTimeoutMs());
return client;
}Example 40
| Project: async-http-client-master File: DefaultSslEngineFactory.java View source code |
private SslContext buildSslContext(AsyncHttpClientConfig config) throws SSLException {
if (config.getSslContext() != null) {
return config.getSslContext();
}
SslContextBuilder sslContextBuilder = //
SslContextBuilder.forClient().sslProvider(//
config.isUseOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK).sessionCacheSize(//
config.getSslSessionCacheSize()).sessionTimeout(config.getSslSessionTimeout());
if (isNonEmpty(config.getEnabledProtocols())) {
sslContextBuilder.protocols(config.getEnabledProtocols());
}
if (isNonEmpty(config.getEnabledCipherSuites())) {
sslContextBuilder.ciphers(Arrays.asList(config.getEnabledCipherSuites()));
}
if (config.isUseInsecureTrustManager()) {
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
}
return configureSslContextBuilder(sslContextBuilder).build();
}Example 41
| Project: bazel-master File: ChannelOptions.java View source code |
@VisibleForTesting
public static ChannelOptions create(RemoteOptions options, @Nullable InputStream credentialsInputStream) {
boolean tlsEnabled = options.tlsEnabled;
SslContext sslContext = null;
String tlsAuthorityOverride = options.tlsAuthorityOverride;
CallCredentials credentials = null;
if (options.tlsEnabled && options.tlsCert != null) {
try {
sslContext = GrpcSslContexts.forClient().trustManager(new File(options.tlsCert)).build();
} catch (SSLException e) {
throw new IllegalArgumentException("SSL error initializing cert " + options.tlsCert + " : " + e);
}
}
if (options.authEnabled) {
try {
GoogleCredentials creds = credentialsInputStream == null ? GoogleCredentials.getApplicationDefault() : GoogleCredentials.fromStream(credentialsInputStream);
if (options.authScope != null) {
creds = creds.createScoped(ImmutableList.of(options.authScope));
}
credentials = MoreCallCredentials.from(creds);
} catch (IOException e) {
throw new IllegalArgumentException("Failed initializing auth credentials for remote cache/execution " + e);
}
}
final int maxMessageSize = Math.max(GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE, options.grpcMaxChunkSizeBytes + CHUNK_MESSAGE_OVERHEAD);
return new ChannelOptions(tlsEnabled, sslContext, tlsAuthorityOverride, credentials, maxMessageSize);
}Example 42
| Project: bugvm-master File: SSLEngineAppData.java View source code |
/**
* Places the data from the buffer into the array of destination
* ByteBuffer objects.
*/
protected int placeTo(ByteBuffer[] dsts, int offset, int length) {
if (buffer == null) {
return 0;
}
int pos = 0;
int len = buffer.length;
int rem;
// write data to the buffers
for (int i = offset; i < offset + length; i++) {
rem = dsts[i].remaining();
// TODO: optimization work - use hasArray, array(), arraycopy
if (len - pos < rem) {
// can fully write remaining data into buffer
dsts[i].put(buffer, pos, len - pos);
pos = len;
// data was written, exit
break;
}
// write chunk of data
dsts[i].put(buffer, pos, rem);
pos += rem;
}
if (pos != len) {
// But if it so, we should allert about internal error.
throw new AlertException(AlertProtocol.INTERNAL_ERROR, new SSLException("The received application data could not be fully written" + "into the destination buffers"));
}
buffer = null;
return len;
}Example 43
| Project: cloudstack-master File: HttpClientWrapper.java View source code |
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLUtils.getSSLContext();
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
X509HostnameVerifier verifier = new X509HostnameVerifier() {
@Override
public void verify(String string, SSLSocket ssls) throws IOException {
}
@Override
public void verify(String string, X509Certificate xc) throws SSLException {
}
@Override
public void verify(String string, String[] strings, String[] strings1) throws SSLException {
}
@Override
public boolean verify(String string, SSLSession ssls) {
return true;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(verifier);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}Example 44
| Project: Correct-master File: ChannelOptions.java View source code |
@VisibleForTesting
public static ChannelOptions create(RemoteOptions options, @Nullable InputStream credentialsInputStream) {
boolean tlsEnabled = options.tlsEnabled;
SslContext sslContext = null;
String tlsAuthorityOverride = options.tlsAuthorityOverride;
CallCredentials credentials = null;
if (options.tlsEnabled && options.tlsCert != null) {
try {
sslContext = GrpcSslContexts.forClient().trustManager(new File(options.tlsCert)).build();
} catch (SSLException e) {
throw new IllegalArgumentException("SSL error initializing cert " + options.tlsCert + " : " + e);
}
}
if (options.authEnabled) {
try {
GoogleCredentials creds = credentialsInputStream == null ? GoogleCredentials.getApplicationDefault() : GoogleCredentials.fromStream(credentialsInputStream);
if (options.authScope != null) {
creds = creds.createScoped(ImmutableList.of(options.authScope));
}
credentials = MoreCallCredentials.from(creds);
} catch (IOException e) {
throw new IllegalArgumentException("Failed initializing auth credentials for remote cache/execution " + e);
}
}
final int maxMessageSize = Math.max(GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE, options.grpcMaxChunkSizeBytes + CHUNK_MESSAGE_OVERHEAD);
return new ChannelOptions(tlsEnabled, sslContext, tlsAuthorityOverride, credentials, maxMessageSize);
}Example 45
| Project: crawler-master File: HTTPSFaker.java View source code |
/**
* Get a HttpClient that accept any HTTP certificate.
*
* @param cm the connection manager to use when creating the new HttpClient
* @return a httpClient that accept any HTTP certificate
*/
@SuppressWarnings("deprecation")
public static DefaultHttpClient getClientThatAllowAnyHTTPS(ThreadSafeClientConnManager cm) {
final TrustManager easyTrustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
final X509HostnameVerifier easyVerifier = new X509HostnameVerifier() {
public boolean verify(String string, SSLSession ssls) {
return true;
}
public void verify(String string, SSLSocket ssls) throws IOException {
}
public void verify(String string, String[] strings, String[] strings1) throws SSLException {
}
public void verify(String string, X509Certificate xc) throws SSLException {
}
};
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { easyTrustManager }, null);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
}
final SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(easyVerifier);
cm.getSchemeRegistry().register(new Scheme(HTTPS, ssf, HTTPS_PORT));
return new DefaultHttpClient(cm);
}Example 46
| Project: dcache-master File: GsiFrameEngine.java View source code |
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length) throws SSLException {
if (src.remaining() < 4) {
return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
}
src.mark();
try {
src.get(header);
if (isSSLv3Packet(header)) {
currentDelegate = gsiEngine;
} else if (isSSLv2HelloPacket(header)) {
currentDelegate = gsiEngine;
} else {
currentDelegate = new FrameEngine();
}
} finally {
src.reset();
}
return currentDelegate.unwrap(src, dsts, offset, length);
}Example 47
| Project: droidtowers-master File: DefaultHttpRequestRetryHandler.java View source code |
/**
* Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine
* if the given method should be retried.
*/
public boolean retryRequest(final IOException exception, int executionCount, final HttpContext context) {
if (exception == null) {
throw new IllegalArgumentException("Exception parameter may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
if (executionCount > this.retryCount) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
if (requestIsAborted(request)) {
return false;
}
if (handleAsIdempotent(request)) {
// Retry if the request is considered idempotent
return true;
}
Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
boolean sent = (b != null && b.booleanValue());
if (!sent || this.requestSentRetryEnabled) {
// if it's OK to retry methods that have been sent
return true;
}
// otherwise do not retry
return false;
}Example 48
| Project: email-master File: TrustManagerFactory.java View source code |
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
String message = null;
X509Certificate certificate = chain[0];
Throwable cause = null;
try {
defaultTrustManager.checkServerTrusted(chain, authType);
new StrictHostnameVerifier().verify(mHost, certificate);
return;
} catch (CertificateException e) {
message = e.getMessage();
cause = e;
} catch (SSLException e) {
message = e.getMessage();
cause = e;
}
// key store or if the host name doesn't match the certificate name
if (!keyStore.isValidCertificate(certificate, mHost, mPort)) {
throw new CertificateChainException(message, chain, cause);
}
}Example 49
| Project: Flock-master File: ImportAccountService.java View source code |
private void handleImportOrGenerateKeyMaterial(Bundle result, DavAccount account, String cipherPassphrase) {
Optional<String[]> saltAndEncryptedKeyMaterial = Optional.absent();
KeyStore.saveMasterPassphrase(getBaseContext(), cipherPassphrase);
DavAccountHelper.setAccountDavHREF(getBaseContext(), account.getDavHostHREF());
try {
DavKeyStore davKeyStore = DavAccountHelper.getDavKeyStore(getBaseContext(), account);
Optional<DavKeyCollection> keyCollection = davKeyStore.getCollection();
if (keyCollection.isPresent()) {
if (keyCollection.get().getKeyMaterialSalt().isPresent() && keyCollection.get().getEncryptedKeyMaterial().isPresent()) {
saltAndEncryptedKeyMaterial = Optional.of(new String[] { keyCollection.get().getKeyMaterialSalt().get(), keyCollection.get().getEncryptedKeyMaterial().get() });
}
} else {
DavKeyStore.createCollection(getBaseContext(), account);
keyCollection = davKeyStore.getCollection();
if (!keyCollection.isPresent()) {
result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_DAV_SERVER_ERROR);
return;
}
}
} catch (PropertyParseException e) {
ErrorToaster.handleBundleError(e, result);
} catch (DavException e) {
ErrorToaster.handleBundleError(e, result);
} catch (SSLException e) {
ErrorToaster.handleBundleError(e, result);
} catch (IOException e) {
ErrorToaster.handleBundleError(e, result);
}
try {
if (saltAndEncryptedKeyMaterial.isPresent())
KeyHelper.importSaltAndEncryptedKeyMaterial(getBaseContext(), saltAndEncryptedKeyMaterial.get());
else
KeyHelper.generateAndSaveSaltAndKeyMaterial(getBaseContext());
result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);
} catch (InvalidMacException e) {
result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_INVALID_CIPHER_PASSPHRASE);
} catch (GeneralSecurityException e) {
ErrorToaster.handleBundleError(e, result);
} catch (IOException e) {
Log.e(TAG, "handleImportOrGenerateKeyMaterial()", e);
result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_CRYPTO_ERROR);
}
}Example 50
| Project: jclouds-master File: IntegrationTestClientExpectTest.java View source code |
@Override
public HttpResponse apply(HttpRequest input) {
// on first request, throw an SSL close_notify exception
if (counter.getAndIncrement() == 0)
throw propagate(new SSLException("Received close_notify during handshake"));
// on other requests, just validate and return 200
assertEquals(renderRequest(input), renderRequest(HttpRequest.builder().method("HEAD").endpoint(URI.create("http://mock/objects/rabbit")).build()));
return HttpResponse.builder().statusCode(200).build();
}Example 51
| Project: jdroid-master File: OkHttpCommand.java View source code |
public R execute(P param) {
try {
return doExecute(param);
} catch (SocketTimeoutException e) {
throw new ConnectionException(e, true);
} catch (ConnectException e) {
throw new ConnectionException(e, false);
} catch (UnknownHostException e) {
throw new ConnectionException(e, false);
} catch (InterruptedIOException e) {
throw new ConnectionException(e, true);
} catch (NoRouteToHostException e) {
throw new ConnectionException(e, false);
} catch (SocketException e) {
String message = e.getMessage();
if (message != null) {
if (message.equals("Software caused connection abort")) {
throw new ConnectionException(e, false);
}
}
Throwable cause = e.getCause();
if (cause != null) {
message = cause.getMessage();
if (message != null) {
if (message.contains("isConnected failed: EHOSTUNREACH (No route to host)")) {
throw new ConnectionException(e, false);
} else if (message.contains("recvfrom failed: ETIMEDOUT (Connection timed out)")) {
throw new ConnectionException(e, true);
} else if (message.contains("recvfrom failed: ECONNRESET (Connection reset by peer)")) {
throw new ConnectionException(e, false);
} else if (message.contains("recvfrom failed: ECONNREFUSED (Connection refused)")) {
throw new ConnectionException(e, false);
} else if (message.contains("sendto failed: ETIMEDOUT (Connection timed out)")) {
throw new ConnectionException(e, true);
} else if (message.equals("Connection reset")) {
throw new ConnectionException(e, true);
}
}
}
throw new UnexpectedException(e);
} catch (SSLHandshakeException e) {
String message = e.getMessage();
if (message != null && message.equals("com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: null")) {
throw new ConnectionException(e, false);
}
throw new UnexpectedException(e);
} catch (SSLException e) {
String message = e.getMessage();
if (message != null) {
if (message.startsWith("Read error:") && message.endsWith("I/O error during system call, Connection reset by peer")) {
throw new ConnectionException(e, true);
} else if (message.startsWith("Read error:") && message.endsWith("I/O error during system call, Connection timed out")) {
throw new ConnectionException(e, true);
} else if (message.startsWith("SSL handshake aborted:") && message.endsWith("I/O error during system call, Connection reset by peer")) {
throw new ConnectionException(e, false);
} else if (message.equals("Connection closed by peer")) {
throw new ConnectionException(e, false);
}
}
throw new UnexpectedException(e);
} catch (ProtocolException e) {
String message = e.getMessage();
if (message != null && message.equals("Too many follow-up requests: 21")) {
throw new ConnectionException(e, false);
}
throw new UnexpectedException(e);
} catch (IOException e) {
String message = e.getMessage();
if (message != null && message.contains("unexpected end of stream on")) {
throw new ConnectionException(e, true);
}
throw new UnexpectedException(e);
}
}Example 52
| Project: k-9-master File: TrustManagerFactory.java View source code |
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
String message = null;
X509Certificate certificate = chain[0];
Throwable cause = null;
try {
defaultTrustManager.checkServerTrusted(chain, authType);
new StrictHostnameVerifier().verify(mHost, certificate);
return;
} catch (CertificateException e) {
message = e.getMessage();
cause = e;
} catch (SSLException e) {
message = e.getMessage();
cause = e;
}
// key store or if the host name doesn't match the certificate name
if (!keyStore.isValidCertificate(certificate, mHost, mPort)) {
throw new CertificateChainException(message, chain, cause);
}
}Example 53
| Project: legacy-jclouds-master File: IntegrationTestClientExpectTest.java View source code |
@Override
public HttpResponse apply(HttpRequest input) {
// on first request, throw an SSL close_notify exception
if (counter.getAndIncrement() == 0)
throw propagate(new SSLException("Received close_notify during handshake"));
// on other requests, just validate and return 200
assertEquals(renderRequest(input), renderRequest(HttpRequest.builder().method("HEAD").endpoint(URI.create("http://mock/objects/rabbit")).build()));
return HttpResponse.builder().statusCode(200).build();
}Example 54
| Project: lightnio-master File: SimpleSSLIOEventDispatch.java View source code |
public void connected(final IOSession session) {
SimpleTestState state = new SimpleTestState(new HeapByteBufferAllocator());
SSLIOSession sslSession = new SSLIOSession(session, this.sslcontext, null);
session.setBufferStatus(state);
IOSession testSession = new LoggingIOSession(sslSession, this.id);
session.setAttribute(TEST_STATE, state);
session.setAttribute(TEST_SESSION, testSession);
session.setAttribute(SSL_SESSION, sslSession);
try {
this.handler.connected(testSession, state);
} catch (IOException ex) {
this.handler.exception(testSession, state, ex);
session.close();
}
try {
sslSession.bind(this.mode);
} catch (SSLException ex) {
this.handler.exception(testSession, state, ex);
testSession.shutdown();
}
}Example 55
| Project: limewire5-ruby-master File: SSLUtilsTest.java View source code |
public void testStartTLS() throws Exception {
try {
SSLUtils.startTLS(new Socket(), BufferUtils.getEmptyBuffer());
fail("expected exception");
} catch (IllegalArgumentException expected) {
}
Socket s = new NIOSocket();
assertTrue(SSLUtils.isStartTLSCapable(s));
assertFalse(SSLUtils.isTLSEnabled(s));
s = SSLUtils.startTLS(s, BufferUtils.getEmptyBuffer());
assertTrue(SSLUtils.isTLSEnabled(s));
try {
SSLUtils.startTLS(new NIOSocket(), ByteBuffer.wrap(new byte[] { 'N', 'O', 'T', 'T', 'L', 'S' }));
fail("expected exception");
} catch (SSLException expected) {
}
ServerSocket ss = new NIOServerSocket();
ss.setSoTimeout(1000);
ss.bind(new InetSocketAddress("localhost", 0));
Socket tls = new TLSSocketFactory().createSocket("localhost", ss.getLocalPort());
tls.getOutputStream().write(StringUtils.toAsciiBytes("OUTPUT"));
Socket accepted = ss.accept();
assertFalse(SSLUtils.isTLSEnabled(accepted));
assertTrue(SSLUtils.isStartTLSCapable(accepted));
byte[] read = new byte[100];
int amt = accepted.getInputStream().read(read);
assertGreaterThan(0, amt);
assertNotEquals("OUTPUT", StringUtils.getASCIIString(read, 0, amt));
Socket converted = SSLUtils.startTLS(accepted, ByteBuffer.wrap(read, 0, amt));
amt = converted.getInputStream().read(read);
// length of string works, since ascii encoding ensures 1-1 mapping between chars and bytes
assertEquals("OUTPUT".length(), amt);
assertEquals("OUTPUT", StringUtils.getASCIIString(read, 0, amt));
converted.close();
accepted.close();
ss.close();
s.close();
}Example 56
| Project: Mace-Swinger-master File: SSLUtils.java View source code |
public static boolean installCerts() {
try {
String host = "maceswinger.com";
int port = (host.split(":").length == 1) ? 443 : Integer.parseInt(host.split(":")[1]);
char[] passphrase = "changeit".toCharArray();
File file = new File(new File(System.getProperty("java.home") + "/lib/security"), "cacerts");
passphrase = "changeit".toCharArray();
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory factory = context.getSocketFactory();
try {
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(15 * 1000);
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
} catch (SSLException e) {
e.printStackTrace();
return false;
} catch (SocketException e) {
e.printStackTrace();
return false;
} catch (SocketTimeoutException e) {
e.printStackTrace();
return false;
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return false;
}
System.out.println("Server sent " + chain.length + " certificate" + (chain.length > 1 ? "s" : ""));
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
sha1.update(cert.getEncoded());
md5.update(cert.getEncoded());
}
System.out.print("Adding to truststore... ");
try {
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
String alias = host + "-" + (i + 1);
ks.setCertificateEntry(alias, cert);
OutputStream out = new FileOutputStream(file.getAbsolutePath());
ks.store(out, "changeit".toCharArray());
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done");
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
doneCerts = true;
return true;
}Example 57
| Project: netty-router-master File: BadClientSilencer.java View source code |
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {
ctx.close();
// To clarify where exceptions are from, imports are not used
if (// Connection reset by peer, Broken pipe
e instanceof java.io.IOException || e instanceof java.nio.channels.ClosedChannelException || e instanceof io.netty.handler.codec.DecoderException || // Bad WebSocket frame
e instanceof io.netty.handler.codec.CorruptedFrameException || // Use https://... to connect to HTTP server
e instanceof java.lang.IllegalArgumentException || // Use http://... to connect to HTTPS server
e instanceof javax.net.ssl.SSLException || e instanceof io.netty.handler.ssl.NotSslRecordException) {
// Maybe client is bad
onBadClient(e);
} else {
// Maybe server is bad
onBadServer(e);
}
}Example 58
| Project: olingo-odata4-master File: RequestRetryHttpClientFactory.java View source code |
@Override
public boolean retryRequest(final IOException exception, final int executionCount, final HttpContext context) {
if (executionCount >= 5) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
final HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}Example 59
| Project: open-mika-master File: SSLEngineAppData.java View source code |
/**
* Places the data from the buffer into the array of destination
* ByteBuffer objects.
*/
protected int placeTo(ByteBuffer[] dsts, int offset, int length) {
if (buffer == null) {
return 0;
}
int pos = 0;
int len = buffer.length;
int rem;
// write data to the buffers
for (int i = offset; i < offset + length; i++) {
rem = dsts[i].remaining();
// TODO: optimization work - use hasArray, array(), arraycopy
if (len - pos < rem) {
// can fully write remaining data into buffer
dsts[i].put(buffer, pos, len - pos);
pos = len;
// data was written, exit
break;
}
// write chunk of data
dsts[i].put(buffer, pos, rem);
pos += rem;
}
if (pos != len) {
// But if it so, we should allert about internal error.
throw new AlertException(AlertProtocol.INTERNAL_ERROR, new SSLException("The received application data could not be fully written" + "into the destination buffers"));
}
buffer = null;
return len;
}Example 60
| Project: property-db-master File: SSLEngineAppData.java View source code |
/**
* Places the data from the buffer into the array of destination
* ByteBuffer objects.
*/
protected int placeTo(ByteBuffer[] dsts, int offset, int length) {
if (buffer == null) {
return 0;
}
int pos = 0;
int len = buffer.length;
int rem;
// write data to the buffers
for (int i = offset; i < offset + length; i++) {
rem = dsts[i].remaining();
// TODO: optimization work - use hasArray, array(), arraycopy
if (len - pos < rem) {
// can fully write remaining data into buffer
dsts[i].put(buffer, pos, len - pos);
pos = len;
// data was written, exit
break;
}
// write chunk of data
dsts[i].put(buffer, pos, rem);
pos += rem;
}
if (pos != len) {
// But if it so, we should allert about internal error.
throw new AlertException(AlertProtocol.INTERNAL_ERROR, new SSLException("The received application data could not be fully written" + "into the destination buffers"));
}
buffer = null;
return len;
}Example 61
| Project: robovm-master File: SSLEngineAppData.java View source code |
/**
* Places the data from the buffer into the array of destination
* ByteBuffer objects.
*/
protected int placeTo(ByteBuffer[] dsts, int offset, int length) {
if (buffer == null) {
return 0;
}
int pos = 0;
int len = buffer.length;
int rem;
// write data to the buffers
for (int i = offset; i < offset + length; i++) {
rem = dsts[i].remaining();
// TODO: optimization work - use hasArray, array(), arraycopy
if (len - pos < rem) {
// can fully write remaining data into buffer
dsts[i].put(buffer, pos, len - pos);
pos = len;
// data was written, exit
break;
}
// write chunk of data
dsts[i].put(buffer, pos, rem);
pos += rem;
}
if (pos != len) {
// But if it so, we should allert about internal error.
throw new AlertException(AlertProtocol.INTERNAL_ERROR, new SSLException("The received application data could not be fully written" + "into the destination buffers"));
}
buffer = null;
return len;
}Example 62
| Project: sdk-dslink-java-master File: ServerManager.java View source code |
private void startHttpsServer(JsonObject conf) {
String certChain = conf.get("certChainFile");
if (certChain == null) {
throw new RuntimeException("certChainFile not configured");
}
String certKey = conf.get("certKeyFile");
if (certKey == null) {
throw new RuntimeException("certChainKey not configured");
}
String certKeyPass = conf.get("certKeyPass");
File cc = new File(certChain);
File ck = new File(certKey);
SslContext ssl;
try {
ssl = SslContext.newServerContext(cc, ck, certKeyPass);
} catch (SSLException e) {
throw new RuntimeException(e);
}
String host = conf.get("host");
int port = conf.get("port");
httpsServer = new Server(host, port, ssl, broker);
httpsServer.start(bossLoop, workerLoop);
}Example 63
| Project: service-proxy-master File: StreamPump.java View source code |
@Override
public void run() {
byte[] buffer = new byte[8192];
int length = 0;
if (stats != null)
stats.registerPump(this);
try {
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
out.flush();
if (stats != null)
bytesTransferred.addAndGet(length);
}
} catch (SocketTimeoutException e) {
} catch (SocketException e) {
} catch (SSLException e) {
} catch (IOException e) {
log.error("Reading from or writing to stream failed: " + e);
} finally {
try {
out.close();
} catch (Exception e) {
}
if (stats != null)
stats.unregisterPump(this);
}
}Example 64
| Project: SocialSDK-master File: SSLUtil.java View source code |
// Wrap for trusting all the certificates
public static DefaultHttpClient wrapHttpClient(DefaultHttpClient base) {
try {
// Create and assign a dummy TrustManager
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] cert, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] cert, String s) throws CertificateException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
// When Apache Client AllowAllHostnameVerifier is strict, this should be used
// Stays here for reference
X509HostnameVerifier verifier = new X509HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
@Override
public void verify(String s, SSLSocket sslSession) throws IOException {
}
@Override
public void verify(String s, String[] ss1, String[] ss2) throws SSLException {
}
@Override
public void verify(String s, X509Certificate cerst) throws SSLException {
}
};
ssf.setHostnameVerifier(verifier);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}Example 65
| Project: spring-xd-master File: SingleNodeApplicationWithDefaultSecurityTest.java View source code |
@Test
public void testSslNotEnabledByDefaultForAdminEndpoints() throws Exception {
try {
restTemplate.getForEntity("https://localhost" + ":" + springXdResource.getAdminPort() + "/modules", Object.class);
} catch (RestClientException e) {
assertThat(e.getCause(), instanceOf(SSLException.class));
}
// HTTP, however, succeeds
ResponseEntity<Object> responseEntity = restTemplate.getForEntity("http://localhost" + ":" + springXdResource.getAdminPort() + "/modules", Object.class);
assertThat(responseEntity.getStatusCode(), equalTo(HttpStatus.OK));
}Example 66
| Project: spring4ws-demos-master File: TwitterStatusListener.java View source code |
@SuppressWarnings("resource")
private String unshorten(String url, int loop) {
if (loop > 2) {
return null;
}
try (CloseableHttpClient defaultHttpClient = HttpClientBuilder.create().disableRedirectHandling().build()) {
HttpHead head = new HttpHead(url);
HttpResponse response = defaultHttpClient.execute(head);
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_MOVED_TEMPORARILY) {
Header locationHeader = response.getFirstHeader("location");
if (locationHeader != null) {
String value = locationHeader.getValue();
if (!value.startsWith("http") && value.startsWith("/")) {
value = "http:/" + value;
}
int nloop = loop + 1;
return unshorten(value, nloop);
}
} else if (status >= 400 && status != HttpStatus.SC_METHOD_NOT_ALLOWED && status != HttpStatus.SC_FORBIDDEN) {
return null;
}
} catch (IllegalStateExceptionIOException | e) {
if (!(e instanceof SSLException || e instanceof ConnectException)) {
}
}
return url;
}Example 67
| Project: test-master File: ChannelOptions.java View source code |
@VisibleForTesting
public static ChannelOptions create(RemoteOptions options, @Nullable InputStream credentialsInputStream) {
boolean tlsEnabled = options.tlsEnabled;
SslContext sslContext = null;
String tlsAuthorityOverride = options.tlsAuthorityOverride;
CallCredentials credentials = null;
if (options.tlsEnabled && options.tlsCert != null) {
try {
sslContext = GrpcSslContexts.forClient().trustManager(new File(options.tlsCert)).build();
} catch (SSLException e) {
throw new IllegalArgumentException("SSL error initializing cert " + options.tlsCert + " : " + e);
}
}
if (options.authEnabled) {
try {
GoogleCredentials creds = credentialsInputStream == null ? GoogleCredentials.getApplicationDefault() : GoogleCredentials.fromStream(credentialsInputStream);
if (options.authScope != null) {
creds = creds.createScoped(ImmutableList.of(options.authScope));
}
credentials = MoreCallCredentials.from(creds);
} catch (IOException e) {
throw new IllegalArgumentException("Failed initializing auth credentials for remote cache/execution " + e);
}
}
final int maxMessageSize = Math.max(GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE, options.grpcMaxChunkSizeBytes + CHUNK_MESSAGE_OVERHEAD);
return new ChannelOptions(tlsEnabled, sslContext, tlsAuthorityOverride, credentials, maxMessageSize);
}Example 68
| Project: user-master File: FailedConnectionListener.java View source code |
@Override
public void handleFailedConnection(PushManager<? extends SimpleApnsPushNotification> pushManager, Throwable cause) {
List<SimpleApnsPushNotification> notifications = new ArrayList<SimpleApnsPushNotification>();
if (cause instanceof SSLException || cause instanceof SSLHandshakeException || cause instanceof ClosedChannelException) {
//cert is probably bad so shut it down.
if (!pushManager.isShutDown()) {
pushManager.unregisterFailedConnectionListener(this);
try {
BlockingQueue notificationQueue = pushManager.getQueue();
if (notificationQueue != null) {
LinkedBlockingQueue<SimpleApnsPushNotification> queue = (LinkedBlockingQueue<SimpleApnsPushNotification>) notificationQueue;
//get messages still in queue
Object[] objectMess = queue.toArray();
for (Object o : objectMess) {
if (o instanceof SimpleApnsPushNotification) {
notifications.add((SimpleApnsPushNotification) o);
}
}
}
pushManager.shutdown();
} catch (InterruptedException ie) {
logger.error("Failed to stop push services", ie);
}
} else {
return;
}
}
//mark all unsent notifications failed
if (notifications != null) {
notifications.forEach( notification -> {
if (notification instanceof APNsNotification) {
try {
((APNsNotification) notification).messageSendFailed(cause);
} catch (Exception e) {
logger.error("failed to track notification in failed connection listener", e);
}
}
if (notification instanceof TestAPNsNotification) {
TestAPNsNotification testAPNsNotification = ((TestAPNsNotification) notification);
testAPNsNotification.setReason(cause);
testAPNsNotification.countdown();
}
});
pushManager.getQueue().clear();
}
logger.error("Failed to register push connection", cause);
}Example 69
| Project: usergrid-master File: FailedConnectionListener.java View source code |
@Override
public void handleFailedConnection(PushManager<? extends SimpleApnsPushNotification> pushManager, Throwable cause) {
List<SimpleApnsPushNotification> notifications = new ArrayList<SimpleApnsPushNotification>();
if (cause instanceof SSLException || cause instanceof SSLHandshakeException || cause instanceof ClosedChannelException) {
//cert is probably bad so shut it down.
if (!pushManager.isShutDown()) {
pushManager.unregisterFailedConnectionListener(this);
try {
BlockingQueue notificationQueue = pushManager.getQueue();
if (notificationQueue != null) {
LinkedBlockingQueue<SimpleApnsPushNotification> queue = (LinkedBlockingQueue<SimpleApnsPushNotification>) notificationQueue;
//get messages still in queue
Object[] objectMess = queue.toArray();
for (Object o : objectMess) {
if (o instanceof SimpleApnsPushNotification) {
notifications.add((SimpleApnsPushNotification) o);
}
}
}
pushManager.shutdown();
} catch (InterruptedException ie) {
logger.error("Failed to stop push services", ie);
}
} else {
return;
}
}
//mark all unsent notifications failed
if (notifications != null) {
notifications.forEach( notification -> {
if (notification instanceof APNsNotification) {
try {
((APNsNotification) notification).messageSendFailed(cause);
} catch (Exception e) {
logger.error("failed to track notification in failed connection listener", e);
}
}
if (notification instanceof TestAPNsNotification) {
TestAPNsNotification testAPNsNotification = ((TestAPNsNotification) notification);
testAPNsNotification.setReason(cause);
testAPNsNotification.countdown();
}
});
pushManager.getQueue().clear();
}
logger.error("Failed to register push connection", cause);
}Example 70
| Project: vertx-stomp-master File: StiltsIT.java View source code |
@Test
public void test() throws URISyntaxException, InterruptedException, TimeoutException, StompException, SSLException {
StompClient client1 = new StompClient("stomp://localhost:61613");
StompClient client2 = new StompClient("stomp://localhost:61613");
client1.connect();
client2.connect();
AtomicReference<StompMessage> frame = new AtomicReference<>();
ClientSubscription subscription1 = client1.subscribe("box").withMessageHandler(frame::set).start();
Headers headers = new DefaultHeaders();
headers.put("header", "value");
client2.send(StompMessages.createStompMessage("box", headers, "hello !"));
await().atMost(10, TimeUnit.SECONDS).until(() -> frame.get() != null);
assertThat(frame.get().getDestination()).isEqualTo("box");
assertThat(frame.get().getContentAsString()).isEqualTo("hello !");
assertThat(frame.get().getHeaders().get("header")).isEqualTo("value");
assertThat(frame.get().getHeaders().get("message-id")).isNotNull();
assertThat(frame.get().getHeaders().get("subscription")).isNotNull();
subscription1.unsubscribe();
client1.disconnect();
client2.disconnect();
}Example 71
| Project: WS-Attacker-master File: TlsWrapperClient.java View source code |
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
X509HostnameVerifier verifier = new X509HostnameVerifier() {
@Override
public void verify(String string, X509Certificate xc) throws SSLException {
}
@Override
public void verify(String string, String[] strings, String[] strings1) throws SSLException {
}
@Override
public boolean verify(String string, SSLSession ssls) {
return true;
}
@Override
public void verify(String string, SSLSocket ssls) throws IOException {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(verifier);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, base.getParams());
} catch (NoSuchAlgorithmException ex) {
return null;
} catch (KeyManagementException ex) {
return null;
}
}Example 72
| Project: xMail-master File: TrustManagerFactory.java View source code |
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
String message = null;
X509Certificate certificate = chain[0];
Throwable cause = null;
try {
defaultTrustManager.checkServerTrusted(chain, authType);
new StrictHostnameVerifier().verify(mHost, certificate);
return;
} catch (CertificateException e) {
message = e.getMessage();
cause = e;
} catch (SSLException e) {
message = e.getMessage();
cause = e;
}
// key store or if the host name doesn't match the certificate name
if (!keyStore.isValidCertificate(certificate, mHost, mPort)) {
throw new CertificateChainException(message, chain, cause);
}
}Example 73
| Project: XobotOS-master File: SSLEngineAppData.java View source code |
/**
* Places the data from the buffer into the array of destination
* ByteBuffer objects.
*/
protected int placeTo(ByteBuffer[] dsts, int offset, int length) {
if (buffer == null) {
return 0;
}
int pos = 0;
int len = buffer.length;
int rem;
// write data to the buffers
for (int i = offset; i < offset + length; i++) {
rem = dsts[i].remaining();
// TODO: optimization work - use hasArray, array(), arraycopy
if (len - pos < rem) {
// can fully write remaining data into buffer
dsts[i].put(buffer, pos, len - pos);
pos = len;
// data was written, exit
break;
}
// write chunk of data
dsts[i].put(buffer, pos, rem);
pos += rem;
}
if (pos != len) {
// But if it so, we should allert about internal error.
throw new AlertException(AlertProtocol.INTERNAL_ERROR, new SSLException("The received application data could not be fully written" + "into the destination buffers"));
}
buffer = null;
return len;
}Example 74
| Project: Yarrn-master File: YarrnApplication.java View source code |
@UiThread
protected void reportException(final Exception ex) {
Log.e("Yarrn", ex.getMessage(), ex);
if (ex instanceof NetworkException || ex.getCause() instanceof SocketException || ex.getCause() instanceof SSLException || ex.getCause() instanceof UnknownHostException || ex.getCause() instanceof NoNetworkException) {
Toast.makeText(getApplicationContext(), R.string.io_exception, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), R.string.unexpected_exception, Toast.LENGTH_LONG).show();
if (prefs.sendErrorReports().get()) {
ACRA.getErrorReporter().handleSilentException(ex);
}
}
}Example 75
| Project: android-sdk-sources-for-api-level-23-master File: SSLExceptionTest.java View source code |
/**
* Test for <code>SSLException(Throwable)</code> constructor
* Assertion: constructs SSLException when <code>cause</code> is not
* null
*/
public void testSSLException04() {
SSLException sE = new SSLException(tCause);
if (sE.getMessage() != null) {
String toS = tCause.toString();
String getM = sE.getMessage();
assertTrue("getMessage() should contain ".concat(toS), (getM.indexOf(toS) != -1));
}
assertNotNull("getCause() must not return null", sE.getCause());
assertEquals("getCause() must return ".concat(tCause.toString()), sE.getCause(), tCause);
}Example 76
| Project: android-sync-master File: DefaultHttpRequestRetryHandler.java View source code |
/**
* Used <code>retryCount</code> and <code>requestSentRetryEnabled</code> to determine
* if the given method should be retried.
*/
public boolean retryRequest(final IOException exception, int executionCount, final HttpContext context) {
if (exception == null) {
throw new IllegalArgumentException("Exception parameter may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
if (executionCount > this.retryCount) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
if (handleAsIdempotent(request)) {
// Retry if the request is considered idempotent
return true;
}
Boolean b = (Boolean) context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
boolean sent = (b != null && b.booleanValue());
if (!sent || this.requestSentRetryEnabled) {
// if it's OK to retry methods that have been sent
return true;
}
// otherwise do not retry
return false;
}Example 77
| Project: Android-wamp-client-master File: WampClientChannelFactoryResolver.java View source code |
@Override
public ChannelFuture createChannel(final ChannelHandler handler, final EventLoopGroup eventLoop, final ObjectMapper objectMapper) throws Exception {
// Initialize SSL when required
final boolean needSsl = uri.getScheme().equalsIgnoreCase("wss");
final SslContext sslCtx0;
if (needSsl && sslCtx == null) {
// Create a default SslContext when we got none provided through the constructor
try {
sslCtx0 = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
} catch (SSLException e) {
throw e;
}
} else if (needSsl) {
sslCtx0 = sslCtx;
} else {
sslCtx0 = null;
}
// Use well-known ports if not explicitly specified
final int port;
if (uri.getPort() == -1) {
if (needSsl)
port = 443;
else
port = 80;
} else
port = uri.getPort();
final WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, WampHandlerConfiguration.WAMP_WEBSOCKET_PROTOCOLS, false, new DefaultHttpHeaders());
Bootstrap b = new Bootstrap();
b.group(eventLoop).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
if (sslCtx0 != null) {
p.addLast(sslCtx0.newHandler(ch.alloc(), uri.getHost(), port));
}
p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), new WebSocketClientProtocolHandler(handshaker, false), new WebSocketFrameAggregator(WampHandlerConfiguration.MAX_WEBSOCKET_FRAME_SIZE), new WampClientWebsocketHandler(handshaker, objectMapper), handler);
}
});
return b.connect(uri.getHost(), port);
}Example 78
| Project: apps-android-wikipedia-master File: ThrowableUtil.java View source code |
private static boolean isNetworkError(@NonNull Throwable e) {
return ThrowableUtil.throwableContainsException(e, HttpRequest.HttpRequestException.class) || ThrowableUtil.throwableContainsException(e, HttpStatusException.class) || ThrowableUtil.throwableContainsException(e, UnknownHostException.class) || ThrowableUtil.throwableContainsException(e, TimeoutException.class) || ThrowableUtil.throwableContainsException(e, SSLException.class);
}Example 79
| Project: ARTPart-master File: SSLExceptionTest.java View source code |
/**
* Test for <code>SSLException(Throwable)</code> constructor
* Assertion: constructs SSLException when <code>cause</code> is not
* null
*/
public void testSSLException04() {
SSLException sE = new SSLException(tCause);
if (sE.getMessage() != null) {
String toS = tCause.toString();
String getM = sE.getMessage();
assertTrue("getMessage() should contain ".concat(toS), (getM.indexOf(toS) != -1));
}
assertNotNull("getCause() must not return null", sE.getCause());
assertEquals("getCause() must return ".concat(tCause.toString()), sE.getCause(), tCause);
}Example 80
| Project: asyncrmi-master File: Filters.java View source code |
private static void addServerEncryption(ChannelHandlerContext ctx, Rule rule) throws SSLException, CertificateException {
// TrustManagerFactory trustManagerFactory = getRuleTrustManager(rule);
Channel ch = ctx.pipeline().channel();
SslContext sslCtx;
ID id = Modules.getInstance().getConfiguration().getNetMap().getId();
if (id != null) {
if (rule.getAuth() != null) {
logger.debug("server using certificate {} from configured id to create ssl context and require client auth: {}", id.getCertificate().getAbsolutePath(), rule.getAuth());
sslCtx = SslContext.newServerContext(null, new File(rule.getAuth()), null, id.getCertificate(), id.getKey(), null, null, null, IdentityCipherSuiteFilter.INSTANCE, null, 0, 0);
SSLEngine engine = sslCtx.newEngine(ch.alloc());
engine.setUseClientMode(false);
engine.setNeedClientAuth(true);
} else {
sslCtx = SslContext.newServerContext(id.getCertificate(), id.getKey());
logger.debug("server using certificate {} from configured id to create ssl context", id.getCertificate().getAbsolutePath());
}
ctx.pipeline().addFirst(sslCtx.newHandler(ch.alloc()));
} else {
SelfSignedCertificate ssc = new SelfSignedCertificate();
if (rule.getAuth() != null) {
logger.debug("server using self signed certificate to create ssl context and require client auth: {}", rule.getAuth());
sslCtx = SslContext.newServerContext(null, new File(rule.getAuth()), null, ssc.certificate(), ssc.privateKey(), null, null, null, IdentityCipherSuiteFilter.INSTANCE, null, 0, 0);
SSLEngine engine = sslCtx.newEngine(ch.alloc());
engine.setUseClientMode(false);
engine.setNeedClientAuth(true);
} else {
logger.debug("server creating self signed certificate to create ssl context");
sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
}
ctx.pipeline().addFirst(sslCtx.newHandler(ch.alloc()));
}
}Example 81
| Project: Atomic-master File: InputThread.java View source code |
/**
* Called to start this Thread reading lines from the IRC server.
* When a line is read, this method calls the handleLine method
* in the PircBot, which may subsequently call an 'onXxx' method
* in the PircBot subclass. If any subclass of Throwable (i.e.
* any Exception or Error) is thrown by your method, then this
* method will print the stack trace to the standard output. It
* is probable that the PircBot may still be functioning normally
* after such a problem, but the existance of any uncaught exceptions
* in your code is something you should really fix.
*/
public void run() {
try {
boolean running = true;
while (running) {
try {
String line = null;
while ((line = _breader.readLine()) != null) {
try {
_bot.handleLine(line);
} catch (Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.flush();
}
}
if (line == null) {
// The server must have disconnected us.
running = false;
}
} catch (InterruptedIOException iioe) {
this.sendRawLine("PING " + (System.currentTimeMillis() / 1000));
} catch (SSLException ssle) {
running = false;
try {
_socket.close();
_isConnected = false;
} catch (Exception e) {
;
}
_bot.onDisconnect();
return;
} catch (IOException ee) {
_socket.close();
_isConnected = false;
running = false;
_bot.onDisconnect();
return;
}
}
} catch (Exception e) {
Log.e("pIRCbot", "inputThread had a booboo", e);
}
// If we reach this point, then we must have disconnected.
try {
_socket.close();
} catch (Exception e) {
}
if (!_disposed) {
_isConnected = false;
_bot.onDisconnect();
}
}Example 82
| Project: carbon-transports-master File: WebSocketTestCase.java View source code |
@Test
public void testText() throws URISyntaxException, InterruptedException, SSLException {
primaryClient.handhshake();
String textSent = "test";
primaryClient.sendText(textSent);
Thread.sleep(threadSleepTime);
String textReceived = primaryClient.getTextReceived();
assertEquals("Not received the same text.", textReceived, textSent);
logger.info("pushing and receiving text data from server completed.");
primaryClient.shutDown();
}Example 83
| Project: categolj2-backend-master File: AuthenticationController.java View source code |
@RequestMapping(value = "login", method = RequestMethod.POST)
String login(@RequestParam("username") String username, @RequestParam("password") String password, UriComponentsBuilder builder, RedirectAttributes attributes, HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.info("attempt to login (username={})", username);
String tokenEndpoint = builder.path("oauth/token").build().toUriString();
HttpEntity<MultiValueMap<String, Object>> ropRequest = authenticationHelper.createRopRequest(username, password);
try {
ResponseEntity<OAuth2AccessToken> result = restTemplate.postForEntity(tokenEndpoint, ropRequest, OAuth2AccessToken.class);
OAuth2AccessToken accessToken = result.getBody();
authenticationHelper.saveAccessTokenInCookie(accessToken, response);
authenticationHelper.writeLoginHistory(accessToken, request, response);
} catch (HttpStatusCodeException e) {
authenticationHelper.handleHttpStatusCodeException(e, attributes);
return "redirect:/login";
} catch (ResourceAccessException e) {
if (e.getCause() instanceof SSLException) {
UriComponentsBuilder b = builder.replacePath("").port(httpsPort);
return login(username, password, b, attributes, request, response);
} else {
throw e;
}
}
return "redirect:/admin";
}Example 84
| Project: CheckIn4Me-master File: OAuth2Request.java View source code |
/** * verify * * @param host * @param cns * @param subjectAlts */ public final //throws SSLException void verify(//throws SSLException String host, //throws SSLException String[] cns, //throws SSLException String[] subjectAlts) { boolean ok = false; try { delegate.verify(host, cns, subjectAlts); } catch (SSLException e) { for (String cn : cns) { if (cn.startsWith("*.")) { try { delegate.verify(host, new String[] { cn.substring(2) }, subjectAlts); ok = true; } catch (Exception e1) { Log.e(TAG, "We are here and I'm not sure why..."); } } } if (!ok) Log.i(TAG, "Failed verification"); } }
Example 85
| Project: Chronicle-Network-master File: NettyClientThroughPutTest.java View source code |
public static void main(String[] args) throws SSLException, InterruptedException {
// Configure SSL.git
@Nullable final SslContext sslCtx;
if (SSL) {
sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
} else {
sslCtx = null;
}
// Configure the client.
@NotNull EventLoopGroup group = new NioEventLoopGroup();
try {
@NotNull Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(@NotNull SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
if (sslCtx != null) {
p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
}
//p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(new MyChannelInboundHandler());
}
});
// Start the client.
ChannelFuture f = b.connect(HOST, PORT).sync();
// Wait until the connection is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down the event loop to terminate all threads.
group.shutdownGracefully();
}
}Example 86
| Project: coprhd-controller-master File: AbstractMountAdapter.java View source code |
@Override
public String getErrorMessage(Throwable t) {
Throwable rootCause = getRootCause(t);
if (rootCause instanceof UnknownHostException) {
return "Unknown host: " + rootCause.getMessage();
} else if (rootCause instanceof ConnectException) {
return "Error connecting: " + rootCause.getMessage();
} else if (rootCause instanceof NoRouteToHostException) {
return "No route to host: " + rootCause.getMessage();
} else if (rootCause instanceof SSLException) {
return "SSL error: " + rootCause.getMessage();
}
return getClosestErrorMessage(t);
}Example 87
| Project: Dirmi-master File: SocketChannelAcceptor.java View source code |
public void run() {
if (mAccepted.isClosed()) {
listener.closed(new ClosedException());
return;
}
Channel channel;
try {
try {
channel = accept();
mAnyAccepted = true;
} catch (SSLException e) {
if (!mAnyAccepted && e.getClass() == SSLException.class) {
close();
}
throw e;
}
} catch (IOException e) {
if (mAccepted.isClosed()) {
listener.closed(e);
} else {
listener.failed(e);
}
return;
}
listener.accepted(channel);
}Example 88
| Project: dropwizard-cassandra-master File: NettySSLOptionsFactory.java View source code |
@Override
public SSLOptions build() {
SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();
if (provider != null) {
sslContextBuilder.sslProvider(provider);
}
if (ciphers != null) {
sslContextBuilder.ciphers(ciphers);
}
if (clientAuth != null) {
sslContextBuilder.clientAuth(clientAuth);
}
if (sessionCacheSize != null) {
sslContextBuilder.sessionCacheSize(sessionCacheSize);
}
if (sessionTimeout != null) {
sslContextBuilder.sessionTimeout(sessionTimeout.toSeconds());
}
if (trustCertChainFile != null) {
sslContextBuilder.trustManager(trustCertChainFile);
}
if (keyManager != null) {
sslContextBuilder.keyManager(keyManager.getKeyCertChainFile(), keyManager.getKeyFile(), keyManager.getKeyPassword());
}
SslContext sslContext;
try {
sslContext = sslContextBuilder.build();
} catch (SSLException e) {
throw new RuntimeException("Unable to build Netty SslContext", e);
}
return new NettySSLOptions(sslContext);
}Example 89
| Project: dungproxy-master File: NettyHttpClient.java View source code |
private SslContext buildingSslContext(KeyManagerFactory keyManagerFactory) throws javax.net.ssl.SSLException {
SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).keyManager(keyManagerFactory);
if (!OpenSsl.isAvailable()) {
log.info("OpenSSL provider not available, falling back to JDK SSL provider");
sslContextBuilder.sslProvider(SslProvider.JDK);
} else {
sslContextBuilder.sslProvider(SslProvider.OPENSSL);
}
return sslContextBuilder.build();
}Example 90
| Project: ECMobile_Android-master File: FileDownloader.java View source code |
public static HttpEntity getHttpEntity(String netAddress, boolean isZip) throws Exception {
try {
// HttpGet连接对象
HttpGet httpGet = new HttpGet(netAddress);
// å?–å¾—HttpClient
HttpClient httpClient = new DefaultHttpClient();
if (isZip) {
httpGet.addHeader("Accept-Encoding", "gzip");
}
// 请求HttpClient,获得HttpResponce
HttpResponse response = httpClient.execute(httpGet);
// 请求�功
int code = response.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
return entity;
} else {
throw new Exception("net work exception,ErrorCode :" + code);
}
} catch (SSLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 91
| Project: elasticsearch-hadoop-master File: NetworkClient.java View source code |
public Response execute(Request request) {
Response response = null;
boolean newNode;
do {
SimpleRequest routedRequest = new SimpleRequest(request.method(), null, request.path(), request.params(), request.body());
newNode = false;
try {
response = currentTransport.execute(routedRequest);
ByteSequence body = routedRequest.body();
if (body != null) {
stats.bytesSent += body.length();
}
} catch (Exception ex) {
if (ex instanceof EsHadoopIllegalStateException) {
throw (EsHadoopException) ex;
}
if (ex instanceof javax.net.ssl.SSLException) {
throw new EsHadoopTransportException(ex);
}
if (ex instanceof BindException || ex instanceof NoRouteToHostException || ex instanceof UnknownHostException) {
throw new EsHadoopTransportException(ex);
}
if (log.isTraceEnabled()) {
log.trace(String.format("Caught exception while performing request [%s][%s] - falling back to the next node in line...", currentNode, request.path()), ex);
}
String failed = currentNode;
failedNodes.put(failed, ex);
newNode = selectNextNode();
log.error(String.format("Node [%s] failed (%s); " + (newNode ? "selected next node [" + currentNode + "]" : "no other nodes left - aborting..."), failed, ex.getMessage()));
if (!newNode) {
throw new EsHadoopNoNodesLeftException(failedNodes);
}
}
} while (newNode);
return response;
}Example 92
| Project: elasticsearch-readonlyrest-plugin-master File: SSLEngineProvider.java View source code |
private void createContext(EnabledSslSettings settings) {
if (settings.getCertchainPem().isPresent() && settings.getPrivkeyPem().isPresent()) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
try {
logger.info("Loading SSL context with certChain=" + settings.getCertchainPem().get().getName() + ", privKey=" + settings.getPrivkeyPem().get().getName());
context = SslContextBuilder.forServer(settings.getCertchainPem().get(), settings.getPrivkeyPem().get(), null).build();
} catch (SSLException e) {
logger.error("Failed to load SSL CertChain & private key!");
e.printStackTrace();
}
return null;
});
// Everything is configured
logger.info("SSL configured through cert_chain and privkey");
return;
} else {
logger.info("SSL cert_chain and privkey not configured, attempting with JKS keystore..");
try {
char[] keyStorePassBa = null;
if (settings.getKeystorePass().isPresent()) {
keyStorePassBa = settings.getKeystorePass().get().toCharArray();
}
// Load the JKS keystore
java.security.KeyStore ks = java.security.KeyStore.getInstance("JKS");
ks.load(new java.io.FileInputStream(settings.getKeystoreFile()), keyStorePassBa);
char[] keyPassBa = null;
if (settings.getKeyPass().isPresent()) {
keyPassBa = settings.getKeyPass().get().toCharArray();
}
// Get PrivKey from keystore
String sslKeyAlias;
if (!settings.getKeyAlias().isPresent()) {
if (ks.aliases().hasMoreElements()) {
String inferredAlias = ks.aliases().nextElement();
logger.info("SSL ssl.key_alias not configured, took first alias in keystore: " + inferredAlias);
sslKeyAlias = inferredAlias;
} else {
throw new SettingsMalformedException("No alias found, therefore key found in keystore!");
}
} else {
sslKeyAlias = settings.getKeyAlias().get();
}
Key key = ks.getKey(sslKeyAlias, keyPassBa);
if (key == null) {
throw new SettingsMalformedException("Private key not found in keystore for alias: " + sslKeyAlias);
}
// Create a PEM of the private key
StringBuilder sb = new StringBuilder();
sb.append("---BEGIN PRIVATE KEY---\n");
sb.append(Base64.getEncoder().encodeToString(key.getEncoded()));
sb.append("\n");
sb.append("---END PRIVATE KEY---");
String privateKey = sb.toString();
logger.info("Discovered key from JKS");
// Get CertChain from keystore
Certificate[] cchain = ks.getCertificateChain(sslKeyAlias);
// Create a PEM of the certificate chain
sb = new StringBuilder();
for (Certificate c : cchain) {
sb.append("-----BEGIN CERTIFICATE-----\n");
sb.append(Base64.getEncoder().encodeToString(c.getEncoded()));
sb.append("\n");
sb.append("-----END CERTIFICATE-----\n");
}
String certChain = sb.toString();
logger.info("Discovered cert chain from JKS");
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
try {
// #TODO expose configuration of sslPrivKeyPem password? Letsencrypt never sets one..
context = SslContextBuilder.forServer(new ByteArrayInputStream(certChain.getBytes(StandardCharsets.UTF_8)), new ByteArrayInputStream(privateKey.getBytes(StandardCharsets.UTF_8)), null).build();
} catch (Exception e) {
logger.error("Failed to load SSL CertChain & private key from Keystore!");
e.printStackTrace();
}
return null;
}
});
} catch (Throwable t) {
logger.error("Failed to load SSL certs and keys from JKS Keystore!");
t.printStackTrace();
}
}
}Example 93
| Project: geo-platform-master File: ConnectorHttpRequestRetryHandler.java View source code |
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (context == null) {
throw new IllegalArgumentException("Parameter HttpContext must not be null");
}
if (executionCount >= this.attemptsCount) {
return false;
}
if (exception instanceof InterruptedIOException) {
// Timeout
return false;
}
if (exception instanceof UnknownHostException) {
// Unknown host
return false;
}
if (exception instanceof ConnectTimeoutException) {
// Connection refused
return false;
}
if (exception instanceof SSLException) {
// SSL handshake exception
return false;
}
HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
if (idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}Example 94
| Project: Grendel-Scan-master File: CustomSSLVerifier.java View source code |
@Override
public final void verify(final String host, final String[] cns, final String[] subjectAlts) {
try {
verifier.verify(host, cns, subjectAlts);
} catch (SSLException e) {
String briefDescription = "A problem was found with the SSL certificate for " + host;
String longDescription = "The SSL certificate for " + host + " had an error: " + e.toString();
String impact = "Problems with SSL certificates can lead to man-in-the-middle attacks, browser errors and more.";
String recomendation = "Use current certificates from recognized Certificate Authorities.";
String references = "";
Finding event = new Finding(null, "SSL Certificate check", FindingSeverity.INFO, "https://" + host, "SSL Certificate Error", briefDescription, longDescription, impact, recomendation, references);
Scan.getInstance().getFindings().addFinding(event);
}
}Example 95
| Project: GrowControl-master File: NetClientManager.java View source code |
public static NetClientManager get() {
if (instance == null) {
synchronized (instanceLock) {
try {
if (instance == null)
instance = new NetClientManager();
} catch (SSLException e) {
instance = null;
log().trace(e);
return null;
} catch (CertificateException e) {
instance = null;
log().trace(e);
return null;
}
}
}
return instance;
}Example 96
| Project: h2o-3-master File: SSLSocketChannelFactoryTest.java View source code |
@Test
public void shouldHandshake() throws IOException, SSLContextException, BrokenBarrierException, InterruptedException {
SSLProperties props = new SSLProperties();
props.put("h2o_ssl_protocol", SecurityUtils.defaultTLSVersion());
props.put("h2o_ssl_jks_internal", getFile("src/test/resources/keystore.jks").getPath());
props.put("h2o_ssl_jks_password", "password");
props.put("h2o_ssl_jts", getFile("src/test/resources/cacerts.jks").getPath());
props.put("h2o_ssl_jts_password", "password");
final SSLSocketChannelFactory factory = new SSLSocketChannelFactory(props);
final CyclicBarrier barrier = new CyclicBarrier(2);
final CyclicBarrier testOne = new CyclicBarrier(2);
final CyclicBarrier testTwo = new CyclicBarrier(2);
final CyclicBarrier testThree = new CyclicBarrier(2);
final boolean[] hs = new boolean[] { true };
Thread client = new ClientThread(factory, testOne, testTwo, testThree, barrier);
client.setDaemon(false);
client.start();
try {
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().setReceiveBufferSize(64 * 1024);
while (true) {
try {
serverSocketChannel.socket().bind(new InetSocketAddress(port));
break;
} catch (BindException e) {
port++;
}
}
barrier.await();
SocketChannel sock = serverSocketChannel.accept();
barrier.reset();
SSLSocketChannel wrappedChannel = (SSLSocketChannel) factory.wrapServerChannel(sock);
assertTrue(wrappedChannel.isHandshakeComplete());
// FIRST TEST: SSL -> SSL SMALL COMMUNICATION
ByteBuffer readBuffer = ByteBuffer.allocate(12);
while (readBuffer.hasRemaining()) {
wrappedChannel.read(readBuffer);
}
readBuffer.flip();
byte[] dst = new byte[12];
readBuffer.get(dst, 0, 12);
readBuffer.clear();
assertEquals("hello, world", new String(dst, "UTF-8"));
testOne.await();
// SECOND TEST: SSL -> SSL BIG COMMUNICATION
int read = 0;
byte[] dstBig = new byte[16];
ByteBuffer readBufferBig = ByteBuffer.allocate(1024);
while (read < 5 * 64 * 1024) {
while (readBufferBig.position() < 16) {
wrappedChannel.read(readBufferBig);
}
readBufferBig.flip();
readBufferBig.get(dstBig, 0, 16);
if (!readBufferBig.hasRemaining()) {
readBufferBig.clear();
} else {
readBufferBig.compact();
}
assertEquals("hello, world" + (read % 9) + "!!!", new String(dstBig, "UTF-8"));
read += 16;
}
testTwo.await();
// THIRD TEST: NON-SSL -> SSL COMMUNICATION
try {
while (readBuffer.hasRemaining()) {
wrappedChannel.read(readBuffer);
}
fail();
} catch (SSLException e) {
}
assertTrue(wrappedChannel.getEngine().isInboundDone());
testThree.await();
// FOURTH TEST: SSL -> NON-SSL COMMUNICATION
readBuffer.clear();
while (readBuffer.hasRemaining()) {
sock.read(readBuffer);
}
readBuffer.flip();
readBuffer.get(dst, 0, 12);
readBuffer.clear();
assertNotEquals("hello, world", new String(dst, "UTF-8"));
} catch (IOExceptionInterruptedException | BrokenBarrierException | e) {
e.printStackTrace();
}
barrier.await();
assertTrue("One of the handshakes failed!", hs[0]);
}Example 97
| Project: http-kit-master File: SSLTest.java View source code |
public static void main(String[] args) throws Exception {
SSLEngine engine = CLIENT_CONTEXT.createSSLEngine();
engine.setUseClientMode(true);
// Create a nonblocking socket channel
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(true);
socketChannel.connect(new InetSocketAddress("google.com", 443));
// int i = 0;
while (!socketChannel.finishConnect()) {
// System.out.println("----------" + i++);
Thread.sleep(50);
// do something until connect completed
}
// Create byte buffers to use for holding application and encoded data
SSLSession session = engine.getSession();
ByteBuffer myNetData = ByteBuffer.allocate(session.getPacketBufferSize());
ByteBuffer peerAppData = ByteBuffer.allocate(session.getApplicationBufferSize());
ByteBuffer peerNetData = ByteBuffer.allocate(session.getPacketBufferSize());
peerNetData.limit(0);
ByteBuffer myAppData = ByteBuffer.wrap(("GET / HTTP/1.1\r\nHost: \r\n\r\n").getBytes());
engine.beginHandshake();
SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus();
while (hs != SSLEngineResult.HandshakeStatus.FINISHED && hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
System.out.println("hs status: " + hs);
switch(hs) {
case NEED_TASK:
Runnable runnable;
while ((runnable = engine.getDelegatedTask()) != null) {
System.out.println("get task " + runnable);
runnable.run();
}
break;
case NEED_UNWRAP:
if (!peerNetData.hasRemaining()) {
peerNetData.clear();
int read = socketChannel.read(peerNetData);
System.out.println("read: " + read + "\t" + peerNetData);
peerNetData.flip();
}
SSLEngineResult status = engine.unwrap(peerNetData, peerAppData);
// peerNetData.compact();
System.out.println("unwrap: " + status);
switch(status.getStatus()) {
case BUFFER_UNDERFLOW:
peerNetData.compact();
// peerNetData.flip();
int read = socketChannel.read(peerNetData);
System.out.println("flip read: " + read + "\t" + peerNetData);
peerNetData.flip();
break;
}
break;
case NEED_WRAP:
myNetData.clear();
SSLEngineResult wrapStatus = engine.wrap(myAppData, myNetData);
System.out.println("wrap: " + wrapStatus);
myNetData.flip();
while (myNetData.hasRemaining()) {
socketChannel.write(myNetData);
}
break;
}
hs = engine.getHandshakeStatus();
}
// https://raw.github.com/http-kit/scale-clojure-web-app/master/results/600k/heap_usage.png
for (int i = 0; i < 5; i++) {
myNetData.clear();
peerAppData.clear();
myAppData = ByteBuffer.wrap(("GET / HTTP/1.1\r\nHost: www.google.co.jp\r\n\r\n").getBytes());
SSLEngineResult wrapStatus = engine.wrap(myAppData, myNetData);
// System.out.println("---------wrap: " + wrapStatus);
myNetData.flip();
while (myNetData.hasRemaining()) {
socketChannel.write(myNetData);
}
peerNetData.clear();
int read = socketChannel.read(peerNetData);
// System.out.println("-------read: " + read + "\t" + peerNetData);
peerNetData.flip();
// Exception in thread "main" javax.net.ssl.SSLException: bad record MAC
SSLEngineResult status = engine.unwrap(peerNetData, peerAppData);
while (status.getStatus() != SSLEngineResult.Status.OK) {
// System.out.println("-------unwrap: " + status);
peerNetData.compact();
read = socketChannel.read(peerNetData);
System.out.println("-------read: " + read + "\t" + peerNetData);
peerNetData.flip();
status = engine.unwrap(peerNetData, peerAppData);
}
peerAppData.flip();
System.out.println(peerAppData);
byte[] data = new byte[peerAppData.remaining()];
peerAppData.get(data);
System.out.println(new String(data));
// peerNetData.compact();
}
// Do initial handshake
// doHandleShake2(socketChannel, engine, myNetData, peerNetData);
}Example 98
| Project: JamVM-PH-master File: SessionImpl.java View source code |
public void prepare(char[] passwd) throws SSLException { try { privateDataSalt = new byte[32]; random.nextBytes(privateDataSalt); GnuPBEKey key = new GnuPBEKey(passwd, privateDataSalt, 1000); Cipher cipher = Cipher.getInstance("PBEWithHMacSHA256AndAES/OFB/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); sealedPrivateData = new SealedObject(privateData, cipher); } catch (IllegalBlockSizeException ibse) { throw new SSLException(ibse); } catch (InvalidKeyException ike) { throw new SSLException(ike); } catch (IOException ioe) { throw new SSLException(ioe); } catch (NoSuchAlgorithmException nsae) { throw new SSLException(nsae); } catch (NoSuchPaddingException nspe) { throw new SSLException(nspe); } }
Example 99
| Project: javamail-1.4.3-master File: CertUtil.java View source code |
public static File get(String host, int port) throws Exception {
char[] passphrase = "changeit".toCharArray();
File file = new File("jssecacerts");
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
logger.info("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory factory = context.getSocketFactory();
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
logger.info("Starting SSL handshake...");
socket.startHandshake();
socket.close();
logger.info("No errors, certificate is already trusted");
} catch (SSLException e) {
e.printStackTrace(System.out);
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
logger.info("Could not obtain server certificate chain");
return null;
}
logger.info("Server sent " + chain.length + " certificate(s):");
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = 0; i < chain.length; i++) {
X509Certificate cert = chain[i];
logger.info(" " + (i + 1) + " Subject " + cert.getSubjectDN());
logger.info(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
logger.info(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
logger.info(" md5 " + toHexString(md5.digest()));
}
int k = 1;
X509Certificate cert = chain[k];
String alias = host + "-" + (k + 1);
ks.setCertificateEntry(alias, cert);
File cafile = new File("jssecacerts");
OutputStream out = new FileOutputStream(cafile);
ks.store(out, passphrase);
out.close();
logger.info(cert);
logger.info("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'");
return cafile;
}Example 100
| Project: jetty-plugin-support-master File: SelectChannelEndPointSslTest.java View source code |
@Test
public void testTcpClose() throws Exception {
// This test replaces SSLSocket() with a very manual SSL client
// so we can close TCP underneath SSL.
SocketChannel client = SocketChannel.open(_connector.socket().getLocalSocketAddress());
client.socket().setSoTimeout(500);
SocketChannel server = _connector.accept();
server.configureBlocking(false);
_manager.register(server);
SSLEngine engine = __sslCtxFactory.newSslEngine();
engine.setUseClientMode(true);
engine.beginHandshake();
ByteBuffer appOut = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
ByteBuffer sslOut = ByteBuffer.allocate(engine.getSession().getPacketBufferSize() * 2);
ByteBuffer appIn = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
ByteBuffer sslIn = ByteBuffer.allocate(engine.getSession().getPacketBufferSize() * 2);
boolean debug = false;
if (debug)
System.err.println(engine.getHandshakeStatus());
int loop = 20;
while (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
if (--loop == 0)
throw new IllegalStateException();
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_WRAP) {
if (debug)
System.err.printf("sslOut %d-%d-%d%n", sslOut.position(), sslOut.limit(), sslOut.capacity());
if (debug)
System.err.printf("appOut %d-%d-%d%n", appOut.position(), appOut.limit(), appOut.capacity());
SSLEngineResult result = engine.wrap(appOut, sslOut);
if (debug)
System.err.println(result);
sslOut.flip();
int flushed = client.write(sslOut);
if (debug)
System.err.println("out=" + flushed);
sslOut.clear();
}
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) {
if (debug)
System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
if (sslIn.position() == 0) {
int filled = client.read(sslIn);
if (debug)
System.err.println("in=" + filled);
}
sslIn.flip();
if (debug)
System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
SSLEngineResult result = engine.unwrap(sslIn, appIn);
if (debug)
System.err.println(result);
if (debug)
System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
if (sslIn.hasRemaining())
sslIn.compact();
else
sslIn.clear();
if (debug)
System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
}
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
Runnable task;
while ((task = engine.getDelegatedTask()) != null) task.run();
if (debug)
System.err.println(engine.getHandshakeStatus());
}
}
if (debug)
System.err.println("\nSay Hello");
// write a message
appOut.put("HelloWorld".getBytes("UTF-8"));
appOut.flip();
SSLEngineResult result = engine.wrap(appOut, sslOut);
if (debug)
System.err.println(result);
sslOut.flip();
int flushed = client.write(sslOut);
if (debug)
System.err.println("out=" + flushed);
sslOut.clear();
appOut.clear();
// read the response
int filled = client.read(sslIn);
if (debug)
System.err.println("in=" + filled);
sslIn.flip();
result = engine.unwrap(sslIn, appIn);
if (debug)
System.err.println(result);
if (sslIn.hasRemaining())
sslIn.compact();
else
sslIn.clear();
appIn.flip();
String reply = new String(appIn.array(), appIn.arrayOffset(), appIn.remaining());
appIn.clear();
Assert.assertEquals("HelloWorld", reply);
SelectorManager.LOG.info("javax.net.ssl.SSLException: Inbound closed... is expected soon");
if (debug)
System.err.println("\nSudden Death");
client.socket().shutdownOutput();
filled = client.read(sslIn);
Assert.assertEquals(-1, filled);
}Example 101
| Project: jetty-spdy-master File: SelectChannelEndPointSslTest.java View source code |
@Test
public void testTcpClose() throws Exception {
// This test replaces SSLSocket() with a very manual SSL client
// so we can close TCP underneath SSL.
SocketChannel client = SocketChannel.open(_connector.socket().getLocalSocketAddress());
client.socket().setSoTimeout(500);
SocketChannel server = _connector.accept();
server.configureBlocking(false);
_manager.register(server);
SSLEngine engine = __sslCtxFactory.newSslEngine();
engine.setUseClientMode(true);
engine.beginHandshake();
ByteBuffer appOut = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
ByteBuffer sslOut = ByteBuffer.allocate(engine.getSession().getPacketBufferSize() * 2);
ByteBuffer appIn = ByteBuffer.allocate(engine.getSession().getApplicationBufferSize());
ByteBuffer sslIn = ByteBuffer.allocate(engine.getSession().getPacketBufferSize() * 2);
boolean debug = false;
if (debug)
System.err.println(engine.getHandshakeStatus());
int loop = 20;
while (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
if (--loop == 0)
throw new IllegalStateException();
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_WRAP) {
if (debug)
System.err.printf("sslOut %d-%d-%d%n", sslOut.position(), sslOut.limit(), sslOut.capacity());
if (debug)
System.err.printf("appOut %d-%d-%d%n", appOut.position(), appOut.limit(), appOut.capacity());
SSLEngineResult result = engine.wrap(appOut, sslOut);
if (debug)
System.err.println(result);
sslOut.flip();
int flushed = client.write(sslOut);
if (debug)
System.err.println("out=" + flushed);
sslOut.clear();
}
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) {
if (debug)
System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
if (sslIn.position() == 0) {
int filled = client.read(sslIn);
if (debug)
System.err.println("in=" + filled);
}
sslIn.flip();
if (debug)
System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
SSLEngineResult result = engine.unwrap(sslIn, appIn);
if (debug)
System.err.println(result);
if (debug)
System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
if (sslIn.hasRemaining())
sslIn.compact();
else
sslIn.clear();
if (debug)
System.err.printf("sslIn %d-%d-%d%n", sslIn.position(), sslIn.limit(), sslIn.capacity());
}
if (engine.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
Runnable task;
while ((task = engine.getDelegatedTask()) != null) task.run();
if (debug)
System.err.println(engine.getHandshakeStatus());
}
}
if (debug)
System.err.println("\nSay Hello");
// write a message
appOut.put("HelloWorld".getBytes("UTF-8"));
appOut.flip();
SSLEngineResult result = engine.wrap(appOut, sslOut);
if (debug)
System.err.println(result);
sslOut.flip();
int flushed = client.write(sslOut);
if (debug)
System.err.println("out=" + flushed);
sslOut.clear();
appOut.clear();
// read the response
int filled = client.read(sslIn);
if (debug)
System.err.println("in=" + filled);
sslIn.flip();
result = engine.unwrap(sslIn, appIn);
if (debug)
System.err.println(result);
if (sslIn.hasRemaining())
sslIn.compact();
else
sslIn.clear();
appIn.flip();
String reply = new String(appIn.array(), appIn.arrayOffset(), appIn.remaining());
appIn.clear();
Assert.assertEquals("HelloWorld", reply);
SelectorManager.LOG.info("javax.net.ssl.SSLException: Inbound closed... is expected soon");
if (debug)
System.err.println("\nSudden Death");
client.socket().shutdownOutput();
filled = client.read(sslIn);
Assert.assertEquals(-1, filled);
}