下面列出了怎么用javax.net.ssl.HandshakeCompletedEvent的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
SSLSession session = event.getSession();
String protocol = session.getProtocol();
String cipherSuite = session.getCipherSuite();
Log.d(TAG, "Handshake completed", new Throwable("This is not Error."));
Log.d(TAG, String.format("Connected with: %s/%s", protocol, cipherSuite));
String peerName = null;
try {
peerName = session.getPeerPrincipal().getName();
} catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
}
Log.d(TAG, String.format("Peer name: %s\n", peerName));
}
public void handshakeCompleted(HandshakeCompletedEvent evt) {
SSLSession session;
String sessionId;
SSLSocket socket;
if (Error.TRACESYSTEMOUT) {
socket = evt.getSocket();
session = evt.getSession();
Error.printSystemOut("SSL handshake completed:");
Error.printSystemOut(
"------------------------------------------------");
Error.printSystemOut("socket: : " + socket);
Error.printSystemOut("cipher suite : " + session.getCipherSuite());
sessionId = StringConverter.byteArrayToHexString(session.getId());
Error.printSystemOut("session id : " + sessionId);
Error.printSystemOut(
"------------------------------------------------");
}
}
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
SSLSession session = event.getSession();
sslConnectionInfos.setPeerHost(session.getPeerHost());
sslConnectionInfos.setPeerPort(session.getPeerPort());
sslConnectionInfos.setProtocol(session.getProtocol());
sslConnectionInfos.setCipherSuite(session.getCipherSuite());
Certificate[] locChain = session.getLocalCertificates();
if (locChain != null) {
X509Certificate[] clientCertificates = Arrays.copyOf(locChain, locChain.length, X509Certificate[].class);
sslConnectionInfos.setClientCertificates(clientCertificates);
}
try {
Certificate[] chain = session.getPeerCertificates();
if (chain != null) {
X509Certificate[] serverCertificates = Arrays.copyOf(chain, chain.length, X509Certificate[].class);
sslConnectionInfos.setServerCertificates(serverCertificates);
}
} catch (SSLPeerUnverifiedException e) {
// do nothing
}
}
HandshakeStatus finishHandshake() {
if (protocolVersion.useTLS13PlusSpec()) {
outputRecord.tc = this;
inputRecord.tc = this;
cipherSuite = handshakeContext.negotiatedCipherSuite;
inputRecord.readCipher.baseSecret =
handshakeContext.baseReadSecret;
outputRecord.writeCipher.baseSecret =
handshakeContext.baseWriteSecret;
}
handshakeContext = null;
outputRecord.handshakeHash.finish();
inputRecord.finishHandshake();
outputRecord.finishHandshake();
isNegotiated = true;
// Tell folk about handshake completion, but do it in a separate thread.
if (transport instanceof SSLSocket &&
sslConfig.handshakeListeners != null &&
!sslConfig.handshakeListeners.isEmpty()) {
HandshakeCompletedEvent hce =
new HandshakeCompletedEvent((SSLSocket)transport, conSession);
//JDK8
Thread thread = new Thread(
null,
new NotifyHandshake(sslConfig.handshakeListeners, hce),
"HandshakeCompletedNotify-Thread",
0);
thread.start();
}
return HandshakeStatus.FINISHED;
}
HandshakeStatus finishHandshake() {
if (protocolVersion.useTLS13PlusSpec()) {
outputRecord.tc = this;
inputRecord.tc = this;
cipherSuite = handshakeContext.negotiatedCipherSuite;
inputRecord.readCipher.baseSecret =
handshakeContext.baseReadSecret;
outputRecord.writeCipher.baseSecret =
handshakeContext.baseWriteSecret;
}
handshakeContext = null;
outputRecord.handshakeHash.finish();
inputRecord.finishHandshake();
outputRecord.finishHandshake();
isNegotiated = true;
// Tell folk about handshake completion, but do it in a separate thread.
if (transport instanceof SSLSocket &&
sslConfig.handshakeListeners != null &&
!sslConfig.handshakeListeners.isEmpty()) {
HandshakeCompletedEvent hce =
new HandshakeCompletedEvent((SSLSocket)transport, conSession);
Thread thread = new Thread(
null,
new NotifyHandshake(sslConfig.handshakeListeners, hce),
"HandshakeCompletedNotify-Thread",
0,
false);
thread.start();
}
return HandshakeStatus.FINISHED;
}
/**
* Create an SSL client socket using the IOR-encoded
* security characteristics.
* Setting want/need client auth on a client socket has no effect so all we can do is use the right host, port, ciphers
*
* @param host The target host name.
* @param port The target connection port.
*
* @return An appropriately configured client SSLSocket.
* @exception IOException if ssl socket can't be obtained and configured.
*/
private Socket createSSLSocket(String host, int port, int requires, int supports) throws IOException {
SSLSocketFactory factory = getSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
socket.setSoTimeout(SOCKET_TIMEOUT_MS);
// get a set of cipher suites appropriate for this connections requirements.
// We request this for each connection, since the outgoing IOR's requirements may be different from
// our server listener requirements.
String[] iorSuites = SSLCipherSuiteDatabase.getCipherSuites(requires, supports, factory.getSupportedCipherSuites());
socket.setEnabledCipherSuites(iorSuites);
if (log.isDebugEnabled()) {
log.debug("Created SSL socket to " + host + ":" + port);
log.debug(" cipher suites:");
for (int i = 0; i < iorSuites.length; i++) {
log.debug(" " + iorSuites[i]);
}
socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent) {
Certificate[] certs = handshakeCompletedEvent.getLocalCertificates();
if (certs != null) {
log.debug("handshake returned local certs count: " + certs.length);
for (int i = 0; i < certs.length; i++) {
Certificate cert = certs[i];
log.debug("cert: " + cert.toString());
}
} else {
log.debug("handshake returned no local certs");
}
}
});
}
return socket;
}
/**
* @throws IOException
* javax.net.ssl.HandshakeCompletedEvent#HandshakeCompletedEvent(SSLSocket sock, SSLSession s)
*/
public final void test_Constructor() throws Exception {
mySSLSession session = new mySSLSession();
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
try {
new HandshakeCompletedEvent(null, null);
fail("Any exception wasn't thrown for null parameters");
} catch (Exception expected) {
}
}
/**
* @throws IOException
* javax.net.ssl.HandshakeCompletedEvent#getCipherSuite()
*/
public final void test_getCipherSuite() throws Exception {
mySSLSession session = new mySSLSession("localhost", 1080, null);
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
assertEquals("SuiteName", event.getCipherSuite());
}
/**
* @throws IOException
* javax.net.ssl.HandshakeCompletedEvent#getLocalCertificates()
*/
public final void test_getLocalCertificates() throws Exception {
mySSLSession session = new mySSLSession("localhost", 1080, null);
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
assertNull(event.getLocalCertificates());
}
/**
* @throws IOException
* javax.net.ssl.HandshakeCompletedEvent#getLocalPrincipal()
*/
public final void test_getLocalPrincipal() throws Exception {
mySSLSession session = new mySSLSession("localhost", 1080, null);
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
assertNull(event.getLocalPrincipal());
}
/**
* @throws IOException
* javax.net.ssl.HandshakeCompletedEvent#getPeerPrincipal()
*/
public final void test_getPeerPrincipal() throws IOException {
mySSLSession session = new mySSLSession("localhost", 1080, null);
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
assertNull(event.getPeerPrincipal());
}
/**
* @throws IOException
* javax.net.ssl.HandshakeCompletedEvent#getSession()
*/
public final void test_getSession() throws IOException {
mySSLSession session = new mySSLSession("localhost", 1080, null);
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, session);
SSLSession ss = event.getSession();
assertNotNull(ss);
assertEquals(session, ss);
}
/**
* @throws IOException
* javax.net.ssl.HandshakeCompletedEvent#getSocket()
*/
public final void test_getSocket() throws IOException {
SSLSocket socket = (SSLSocket) SSLSocketFactory.getDefault().createSocket();
HandshakeCompletedEvent event = new HandshakeCompletedEvent(socket, null);
SSLSocket ss = event.getSocket();
assertNotNull(ss);
assertEquals(socket, ss);
}
public void test_SSLSocket_HandshakeCompletedListener_RuntimeException() throws Exception {
final Thread self = Thread.currentThread();
final UncaughtExceptionHandler original = self.getUncaughtExceptionHandler();
final RuntimeException expectedException = new RuntimeException("expected");
final TestUncaughtExceptionHandler test = new TestUncaughtExceptionHandler();
self.setUncaughtExceptionHandler(test);
final TestSSLContext c = TestSSLContext.create();
final SSLSocket client = (SSLSocket)
c.clientContext.getSocketFactory().createSocket(c.host, c.port);
final SSLSocket server = (SSLSocket) c.serverSocket.accept();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Void> future = executor.submit(new Callable<Void>() {
@Override public Void call() throws Exception {
server.startHandshake();
return null;
}
});
executor.shutdown();
client.addHandshakeCompletedListener(new HandshakeCompletedListener() {
public void handshakeCompleted(HandshakeCompletedEvent event) {
throw expectedException;
}
});
client.startHandshake();
future.get();
client.close();
server.close();
c.close();
assertSame(expectedException, test.actualException);
self.setUncaughtExceptionHandler(original);
}
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
complete = true;
}
NotifyHandshake(
Map<HandshakeCompletedListener,AccessControlContext> listeners,
HandshakeCompletedEvent event) {
this.targets = new HashSet<>(listeners.entrySet()); // clone
this.event = event;
}
public void handshakeCompleted(HandshakeCompletedEvent e) {
GlobalLogger.instance().getApplicationLogger().debug(TextEvent.Topic.CORE, "Handshake succesful for channel ", this);
}
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
completed = true;
}
@Test
public void testRenegotiateFail() throws Exception {
// If RFC5746 is supported, renegotiation will always work (and will
// always be secure)
if (TesterSupport.RFC_5746_SUPPORTED) {
return;
}
Tomcat tomcat = getTomcatInstance();
File appDir = new File(getBuildDirectory(), "webapps/examples");
// app dir is relative to server home
tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
TesterSupport.initSsl(tomcat);
// Default - MITM attack prevented
tomcat.start();
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(null, TesterSupport.getTrustManagers(), null);
SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", getPort());
socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
handshakeDone = true;
}
});
OutputStream os = socket.getOutputStream();
os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.0\n".getBytes());
os.flush();
InputStream is = socket.getInputStream();
// Make sure the NIO connector has read the request before the handshake
Thread.sleep(100);
socket.startHandshake();
os = socket.getOutputStream();
try {
os.write("Host: localhost\n\n".getBytes());
} catch (IOException ex) {
ex.printStackTrace();
fail("Re-negotiation failed");
}
Reader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);
String line = br.readLine();
while (line != null) {
// For testing System.out.println(line);
line = br.readLine();
}
if (!handshakeDone) {
// success - we timed-out without handshake
return;
}
fail("Re-negotiation worked");
}
NotifyHandshake(
Map<HandshakeCompletedListener,AccessControlContext> listeners,
HandshakeCompletedEvent event) {
this.targets = new HashSet<>(listeners.entrySet()); // clone
this.event = event;
}
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
completed = true;
}
@Test
public void testRenegotiateFail() throws Exception {
// If RFC5746 is supported, renegotiation will always work (and will
// always be secure)
if (TesterSupport.RFC_5746_SUPPORTED) {
return;
}
Tomcat tomcat = getTomcatInstance();
File appDir = new File(getBuildDirectory(), "webapps/examples");
// app dir is relative to server home
tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
TesterSupport.initSsl(tomcat);
// Default - MITM attack prevented
tomcat.start();
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(null, TesterSupport.getTrustManagers(), null);
SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", getPort());
socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
handshakeDone = true;
}
});
OutputStream os = socket.getOutputStream();
os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.0\n".getBytes());
os.flush();
InputStream is = socket.getInputStream();
// Make sure the NIO connector has read the request before the handshake
Thread.sleep(100);
socket.startHandshake();
os = socket.getOutputStream();
try {
os.write("Host: localhost\n\n".getBytes());
} catch (IOException ex) {
ex.printStackTrace();
fail("Re-negotiation failed");
}
Reader r = new InputStreamReader(is);
BufferedReader br = new BufferedReader(r);
String line = br.readLine();
while (line != null) {
// For testing System.out.println(line);
line = br.readLine();
}
if (!handshakeDone) {
// success - we timed-out without handshake
return;
}
fail("Re-negotiation worked");
}
private void invokeHandshakeListeners() {
final HandshakeCompletedEvent event = new HandshakeCompletedEvent(this, getSession());
for (HandshakeCompletedListener listener : new ArrayList<>(handshakeCompletedListenerList)) {
listener.handshakeCompleted(event);
}
}
@Override
public void handshakeCompleted(final HandshakeCompletedEvent event) {
latch.countDown();
Assert.assertArrayEquals(expectedSessionId, event.getSession().getId());
}
@Override
public void handshakeCompleted(final HandshakeCompletedEvent event) {
futureSessionId.value = event.getSession().getId();
}
public void handshakeCompleted(HandshakeCompletedEvent event) {
}
public void handshakeCompleted(HandshakeCompletedEvent event) {
if (event != null) completeDone = true;
}
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
}