本文整理汇总了Java中javax.net.ssl.SSLSocket.startHandshake方法的典型用法代码示例。如果您正苦于以下问题:Java SSLSocket.startHandshake方法的具体用法?Java SSLSocket.startHandshake怎么用?Java SSLSocket.startHandshake使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.net.ssl.SSLSocket
的用法示例。
在下文中一共展示了SSLSocket.startHandshake方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: upgradeToTls
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
private void upgradeToTls(Socket socket) throws KeyStoreException, IOException, NoSuchAlgorithmException,
CertificateException, UnrecoverableKeyException, KeyManagementException {
KeyStore keyStore = keyStoreProvider.getKeyStore();
String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm);
keyManagerFactory.init(keyStore, keyStoreProvider.getPassword());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
sslSocket.setUseClientMode(false);
sslSocket.startHandshake();
input = Okio.buffer(Okio.source(sslSocket.getInputStream()));
output = Okio.buffer(Okio.sink(sslSocket.getOutputStream()));
}
示例2: initSocket
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
@Override
protected void initSocket() throws IOException {
SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(destination.getAddress(), destination.getPort());
sslSocket.addHandshakeCompletedListener(handshakeCompletedEvent -> {
try {
LOGGER.debug("Connected [" + handshakeCompletedEvent.getSource() + ", " + sslSocket.getSession().getPeerCertificateChain()[0].getSubjectDN() + "]");
} catch (SSLPeerUnverifiedException e) {
LOGGER.warn(e.getMessage(), e);
}
}
);
sslSocket.startHandshake();
this.socket = sslSocket;
}
示例3: verifyHostname
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
/**
* Verify hostname against certificate
* @param sslSocket Socket
* @param host Host name
* @throws IOException Exception if host name is not verified
*/
private void verifyHostname(SSLSocket sslSocket, String host) throws IOException {
// Make sure we started handshake before verifying
sslSocket.startHandshake();
SSLSession session = sslSocket.getSession();
if (session == null) {
throw new SSLException("Hostname '" + host + "' was not verified (no session)");
}
if (!hostnameVerifier.verify(host, session)) {
throw new SSLPeerUnverifiedException("Hostname '" + host + "' was not verified (" + session.getPeerPrincipal() + ")");
}
if (Logger.DEBUG) { Log.d(TAG, "Connected to " + session.getPeerHost() + " using " + session.getProtocol() + " (" + session.getCipherSuite() + ")"); }
}
示例4: testSSLSocket
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
private boolean testSSLSocket(SSLSocket sslSocket) {
try {
if(DEBUG_ALL) System.out.println("Starting SSL handshake");
sslSocket.setSoTimeout(0);
sslSocket.startHandshake();
return true;
} catch (Exception e) {
if(DEBUG_ALL) e.printStackTrace();
return false;
}
}
示例5: processHandshakeFailure
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
private void processHandshakeFailure(Socket raw) throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] {UNTRUSTED_TRUST_MANAGER}, new SecureRandom());
SSLSocketFactory sslSocketFactory = context.getSocketFactory();
SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(
raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true);
try {
socket.startHandshake(); // we're testing a handshake failure
throw new AssertionError();
} catch (IOException expected) {
}
socket.close();
}
示例6: get
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
public static void get(String host, int port, KeyStore keyStore) throws Exception {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] {tm}, null);
LOGGER.info("Iniciando conexão com: " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(host, port);
try {
socket.setSoTimeout(30 * 1000);
socket.startHandshake();
socket.close();
} catch (Exception e) {
LOGGER.info(e.toString());
}
X509Certificate[] chain = tm.chain;
if (chain == null) {
LOGGER.info("Não foi possivel obter a cadeia de certificados");
}
LOGGER.info("O servidor enviou " + chain.length + " certificado(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());
String alias = host + "-" + (i);
keyStore.setCertificateEntry(alias, cert);
LOGGER.info("Certificado adicionado usando alias: '" + alias + "'");
}
}
示例7: sslNegotiation
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
/**
* SSL/TLS negotiation. Acquires an SSL socket of a control
* connection and carries out handshake processing.
* @throws java.io.IOException If server negotiation fails
*/
protected void sslNegotiation() throws IOException {
plainSocket = _socket_;
initSslContext();
SSLSocketFactory ssf = context.getSocketFactory();
String ip = _socket_.getInetAddress().getHostAddress();
int port = _socket_.getPort();
SSLSocket socket =
(SSLSocket) ssf.createSocket(_socket_, ip, port, false);
socket.setEnableSessionCreation(isCreation);
socket.setUseClientMode(isClientMode);
// server mode
if (!isClientMode) {
socket.setNeedClientAuth(isNeedClientAuth);
socket.setWantClientAuth(isWantClientAuth);
}
if (protocols != null) {
socket.setEnabledProtocols(protocols);
}
if (suites != null) {
socket.setEnabledCipherSuites(suites);
}
socket.startHandshake();
_socket_ = socket;
_controlInput_ = new BufferedReader(new InputStreamReader(
socket .getInputStream(), getControlEncoding()));
_controlOutput_ = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), getControlEncoding()));
}
示例8: connectSocket
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
public Socket connectSocket(
final int connectTimeout,
final Socket socket,
final HttpHost host,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpContext context) throws IOException {
Args.notNull(host, "HTTP host");
Args.notNull(remoteAddress, "Remote address");
final Socket sock = socket != null ? socket : createSocket(context);
if (localAddress != null) {
sock.bind(localAddress);
}
try {
sock.connect(remoteAddress, connectTimeout);
} catch (final IOException ex) {
try {
sock.close();
} catch (final IOException ignore) {
}
throw ex;
}
// Setup SSL layering if necessary
if (sock instanceof SSLSocket) {
final SSLSocket sslsock = (SSLSocket) sock;
sslsock.startHandshake();
verifyHostname(sslsock, host.getHostName());
return sock;
} else {
return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);
}
}
示例9: createLayeredSocket
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
public Socket createLayeredSocket(
final Socket socket,
final String target,
final int port,
final HttpContext context) throws IOException {
final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(
socket,
target,
port,
true);
internalPrepareSocket(sslsock);
sslsock.startHandshake();
verifyHostname(sslsock, target);
return sslsock;
}
示例10: verifyHostName
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
/**
* Verifies that the given hostname in certicifate is the hostname we are trying to connect to
* http://www.cvedetails.com/cve/CVE-2012-5783/
* @param host
* @param ssl
* @throws IOException
*/
private static void verifyHostName(String host, SSLSocket ssl)
throws IOException {
if (host == null) {
throw new IllegalArgumentException("host to verify was null");
}
SSLSession session = ssl.getSession();
if (session == null) {
// In our experience this only happens under IBM 1.4.x when
// spurious (unrelated) certificates show up in the server's chain.
// Hopefully this will unearth the real problem:
InputStream in = ssl.getInputStream();
in.available();
/*
If you're looking at the 2 lines of code above because you're
running into a problem, you probably have two options:
#1. Clean up the certificate chain that your server
is presenting (e.g. edit "/etc/apache2/server.crt" or
wherever it is your server's certificate chain is
defined).
OR
#2. Upgrade to an IBM 1.5.x or greater JVM, or switch to a
non-IBM JVM.
*/
// If ssl.getInputStream().available() didn't cause an exception,
// maybe at least now the session is available?
session = ssl.getSession();
if (session == null) {
// If it's still null, probably a startHandshake() will
// unearth the real problem.
ssl.startHandshake();
// Okay, if we still haven't managed to cause an exception,
// might as well go for the NPE. Or maybe we're okay now?
session = ssl.getSession();
}
}
Certificate[] certs = session.getPeerCertificates();
verifyHostName(host.trim().toLowerCase(Locale.US), (X509Certificate) certs[0]);
}
示例11: upgradeToTls
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
/**
* Create an {@code SSLSocket} and perform the TLS handshake and certificate
* validation.
*/
private void upgradeToTls(TunnelRequest tunnelRequest) throws IOException {
Platform platform = Platform.get();
// Make an SSL Tunnel on the first message pair of each SSL + proxy connection.
if (requiresTunnel()) {
makeTunnel(tunnelRequest);
}
// Create the wrapper over connected socket.
socket = route.address.sslSocketFactory
.createSocket(socket, route.address.uriHost, route.address.uriPort, true /* autoClose */);
SSLSocket sslSocket = (SSLSocket) socket;
if (route.modernTls) {
platform.enableTlsExtensions(sslSocket, route.address.uriHost);
} else {
platform.supportTlsIntolerantServer(sslSocket);
}
boolean useNpn = route.modernTls && route.address.transports.contains("spdy/3");
if (useNpn) {
platform.setNpnProtocols(sslSocket, NPN_PROTOCOLS);
}
// Force handshake. This can throw!
sslSocket.startHandshake();
// Verify that the socket's certificates are acceptable for the target host.
if (!route.address.hostnameVerifier.verify(route.address.uriHost, sslSocket.getSession())) {
throw new IOException("Hostname '" + route.address.uriHost + "' was not verified");
}
out = sslSocket.getOutputStream();
in = sslSocket.getInputStream();
streamWrapper();
byte[] selectedProtocol;
if (useNpn && (selectedProtocol = platform.getNpnSelectedProtocol(sslSocket)) != null) {
if (Arrays.equals(selectedProtocol, SPDY3)) {
sslSocket.setSoTimeout(0); // SPDY timeouts are set per-stream.
spdyConnection = new SpdyConnection.Builder(route.address.getUriHost(), true, in, out)
.build();
spdyConnection.sendConnectionHeader();
} else if (!Arrays.equals(selectedProtocol, HTTP_11)) {
throw new IOException(
"Unexpected NPN transport " + new String(selectedProtocol, "ISO-8859-1"));
}
}
}
示例12: startHandshake
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
private SSLSocket startHandshake(SSLSocketFactory factory)
throws IOException {
if (ldapConnection == null) {
throw new IllegalStateException("LDAP connection has not been set."
+ " TLS requires an existing LDAP connection.");
}
if (factory != currentFactory) {
// Create SSL socket layered over the existing connection
sslSocket = (SSLSocket) factory.createSocket(ldapConnection.sock,
ldapConnection.host, ldapConnection.port, false);
currentFactory = factory;
if (debug) {
System.out.println("StartTLS: Created socket : " + sslSocket);
}
}
if (suites != null) {
sslSocket.setEnabledCipherSuites(suites);
if (debug) {
System.out.println("StartTLS: Enabled cipher suites");
}
}
// Connection must be quite for handshake to proceed
try {
if (debug) {
System.out.println(
"StartTLS: Calling sslSocket.startHandshake");
}
sslSocket.startHandshake();
if (debug) {
System.out.println(
"StartTLS: + Finished sslSocket.startHandshake");
}
// Replace original streams with the new SSL streams
ldapConnection.replaceStreams(sslSocket.getInputStream(),
sslSocket.getOutputStream());
if (debug) {
System.out.println("StartTLS: Replaced IO Streams");
}
} catch (IOException e) {
if (debug) {
System.out.println("StartTLS: Got IO error during handshake");
e.printStackTrace();
}
sslSocket.close();
isClosed = true;
throw e; // pass up exception
}
return sslSocket;
}
示例13: testRenegotiateWorks
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
@Test
public void testRenegotiateWorks() throws Exception {
Tomcat tomcat = getTomcatInstance();
Assume.assumeTrue("SSL renegotiation has to be supported for this test",
TesterSupport.isRenegotiationSupported(getTomcatInstance()));
File appDir = new File(getBuildDirectory(), "webapps/examples");
// app dir is relative to server home
tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());
TesterSupport.initSsl(tomcat);
tomcat.start();
SSLContext sslCtx = SSLContext.getInstance("TLS");
sslCtx.init(null, TesterSupport.getTrustManagers(), null);
SSLSocketFactory socketFactory =
new TesterSupport.NoSSLv2SocketFactory(sslCtx.getSocketFactory());
SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost",
getPort());
OutputStream os = socket.getOutputStream();
os.write("GET /examples/servlets/servlet/HelloWorldExample HTTP/1.1\n".getBytes());
os.flush();
socket.startHandshake();
try {
os.write("Host: localhost\n\n".getBytes());
} catch (IOException ex) {
ex.printStackTrace();
fail("Re-negotiation failed");
}
InputStream is = socket.getInputStream();
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();
}
}
示例14: verify
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
public final void verify(String host, SSLSocket ssl)
throws IOException {
if(host == null) {
throw new NullPointerException("host to verify is null");
}
SSLSession session = ssl.getSession();
if(session == null) {
// In our experience this only happens under IBM 1.4.x when
// spurious (unrelated) certificates show up in the server'
// chain. Hopefully this will unearth the real problem:
InputStream in = ssl.getInputStream();
in.available();
/*
If you're looking at the 2 lines of code above because
you're running into a problem, you probably have two
options:
#1. Clean up the certificate chain that your server
is presenting (e.g. edit "/etc/apache2/server.crt"
or wherever it is your server's certificate chain
is defined).
OR
#2. Upgrade to an IBM 1.5.x or greater JVM, or switch
to a non-IBM JVM.
*/
// If ssl.getInputStream().available() didn't cause an
// exception, maybe at least now the session is available?
session = ssl.getSession();
if(session == null) {
// If it's still null, probably a startHandshake() will
// unearth the real problem.
ssl.startHandshake();
// Okay, if we still haven't managed to cause an exception,
// might as well go for the NPE. Or maybe we're okay now?
session = ssl.getSession();
}
}
Certificate[] certs = session.getPeerCertificates();
X509Certificate x509 = (X509Certificate) certs[0];
verify(host, x509);
}
示例15: verify
import javax.net.ssl.SSLSocket; //导入方法依赖的package包/类
public final void verify(final String host, final SSLSocket ssl)
throws IOException {
if(host == null) {
throw new NullPointerException("host to verify is null");
}
SSLSession session = ssl.getSession();
if(session == null) {
// In our experience this only happens under IBM 1.4.x when
// spurious (unrelated) certificates show up in the server'
// chain. Hopefully this will unearth the real problem:
final InputStream in = ssl.getInputStream();
in.available();
/*
If you're looking at the 2 lines of code above because
you're running into a problem, you probably have two
options:
#1. Clean up the certificate chain that your server
is presenting (e.g. edit "/etc/apache2/server.crt"
or wherever it is your server's certificate chain
is defined).
OR
#2. Upgrade to an IBM 1.5.x or greater JVM, or switch
to a non-IBM JVM.
*/
// If ssl.getInputStream().available() didn't cause an
// exception, maybe at least now the session is available?
session = ssl.getSession();
if(session == null) {
// If it's still null, probably a startHandshake() will
// unearth the real problem.
ssl.startHandshake();
// Okay, if we still haven't managed to cause an exception,
// might as well go for the NPE. Or maybe we're okay now?
session = ssl.getSession();
}
}
final Certificate[] certs = session.getPeerCertificates();
final X509Certificate x509 = (X509Certificate) certs[0];
verify(host, x509);
}