javax.net.ssl.SSLSocket#getSession ( )源码实例Demo

下面列出了javax.net.ssl.SSLSocket#getSession ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * Verify the hostname of the certificate used by the other end of a
 * connected socket.  You MUST call this if you did not supply a hostname
 * to {@link #createSocket()}.  It is harmless to call this method
 * redundantly if the hostname has already been verified.
 *
 * <p>Wildcard certificates are allowed to verify any matching hostname,
 * so "foo.bar.example.com" is verified if the peer has a certificate
 * for "*.example.com".
 *
 * @param socket An SSL socket which has been connected to a server
 * @param hostname The expected hostname of the remote server
 * @throws IOException if something goes wrong handshaking with the server
 * @throws SSLPeerUnverifiedException if the server cannot prove its identity
 *
 * @hide
 */
public static void verifyHostname(Socket socket, String hostname) throws IOException {
    if (!(socket instanceof SSLSocket)) {
        throw new IllegalArgumentException("Attempt to verify non-SSL socket");
    }

    if (!isSslCheckRelaxed()) {
        // The code at the start of OpenSSLSocketImpl.startHandshake()
        // ensures that the call is idempotent, so we can safely call it.
        SSLSocket ssl = (SSLSocket) socket;
        ssl.startHandshake();

        SSLSession session = ssl.getSession();
        if (session == null) {
            throw new SSLException("Cannot verify SSL socket without session");
        }
        if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)) {
            throw new SSLPeerUnverifiedException("Cannot verify hostname: " + hostname);
        }
    }
}
 
源代码2 项目: PixivforMuzei3   文件: RubySSLSocketFactory.java
@Override
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose) throws IOException
{
    InetAddress address = plainSocket.getInetAddress();
    Log.i("!", "Address: " + address.getHostAddress());
    if (autoClose)
    {
        plainSocket.close();
    }
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory) SSLCertificateSocketFactory.getDefault(0);
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, port);
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());
    SSLSession session = ssl.getSession();
    Log.i("!", "Protocol " + session.getProtocol() + " PeerHost " + session.getPeerHost() +
            " CipherSuite " + session.getCipherSuite());
    return ssl;
}
 
源代码3 项目: nv-websocket-client   文件: SocketConnector.java
private void verifyHostname(SSLSocket socket, String hostname) throws HostnameUnverifiedException
{
    if (mVerifyHostname == false)
    {
        // Skip hostname verification.
        return;
    }

    // Hostname verifier.
    OkHostnameVerifier verifier = OkHostnameVerifier.INSTANCE;

    // The SSL session.
    SSLSession session = socket.getSession();

    // Verify the hostname.
    if (verifier.verify(hostname, session))
    {
        // Verified. No problem.
        return;
    }

    // The certificate of the peer does not match the expected hostname.
    throw new HostnameUnverifiedException(socket, hostname);
}
 
源代码4 项目: buddycloud-android   文件: TLSSNISocketFactory.java
@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;
}
 
源代码5 项目: baratine   文件: SocketWrapperBar.java
/**
 * Returns the bits in the socket.
 */
@Override
public int cipherBits()
{
  if (! (_s instanceof SSLSocket))
    return super.cipherBits();
  
  SSLSocket sslSocket = (SSLSocket) _s;
  
  SSLSession sslSession = sslSocket.getSession();
  
  if (sslSession != null)
    return _sslKeySizes.get(sslSession.getCipherSuite());
  else
    return 0;
}
 
源代码6 项目: baratine   文件: SocketChannelWrapperBar.java
/**
 * Returns the secure cipher algorithm.
 */
@Override
public String secureProtocol()
{
  SSLSocket sslSocket = _sslSocket;
  
  if (sslSocket == null) {
    return super.secureProtocol();
  }
  
  SSLSession sslSession = sslSocket.getSession();
  
  if (sslSession != null) {
    return sslSession.getProtocol();
  }
  else {
    return null;
  }
}
 
源代码7 项目: activemq-artemis   文件: SslBrokerServiceTest.java
private void makeSSLConnection(SSLContext context,
                               String enabledSuites[],
                               TransportConnector connector) throws Exception, UnknownHostException, SocketException {
   SSLSocket sslSocket = (SSLSocket) context.getSocketFactory().createSocket("localhost", connector.getUri().getPort());

   if (enabledSuites != null) {
      sslSocket.setEnabledCipherSuites(enabledSuites);
   }
   sslSocket.setSoTimeout(5000);

   SSLSession session = sslSocket.getSession();
   sslSocket.startHandshake();
   LOG.info("cyphersuite: " + session.getCipherSuite());
   LOG.info("peer port: " + session.getPeerPort());
   LOG.info("peer cert: " + session.getPeerCertificateChain()[0].toString());
}
 
源代码8 项目: PacketProxy   文件: Https.java
public static String getCommonName(InetSocketAddress addr) throws Exception {
	SSLSocketFactory ssf = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) ssf.createSocket(addr.getAddress(), addr.getPort());
    socket.startHandshake();
    SSLSession session = socket.getSession();
    X509Certificate[] servercerts = (X509Certificate[]) session.getPeerCertificates();

    Pattern pattern = Pattern.compile("CN=([^,]+)", Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(servercerts[0].getSubjectDN().getName());
    if (matcher.find()) {
    	return matcher.group(1);
    }
    return "";
}
 
源代码9 项目: j2objc   文件: SSLSocketTest.java
public void test_SSLSocket_getSession() throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket ssl = (SSLSocket) sf.createSocket();
    SSLSession session = ssl.getSession();
    assertNotNull(session);
    assertFalse(session.isValid());
}
 
源代码10 项目: lams   文件: TLSProtocolSocketFactory.java
/**
 * Verifies the peer's hostname using the configured {@link HostnameVerifier}.
 * 
 * @param socket the socket connected to the peer whose hostname is to be verified.
 * 
 * @throws SSLException if the hostname does not verify against the peer's certificate, 
 *          or if there is an error in performing the evaluation
 */
protected void verifyHostname(Socket socket) throws SSLException {
    if (hostnameVerifier == null) {
        return;
    }
    
    if (!(socket instanceof SSLSocket)) {
        return;
    }
    
    SSLSocket sslSocket = (SSLSocket) socket;
    
    try {
        SSLSession sslSession = sslSocket.getSession();
        String hostname = sslSession.getPeerHost();
        
        if (!hostnameVerifier.verify(hostname, sslSession)) {
            throw new SSLPeerUnverifiedException("SSL peer failed hostname validation for name: " + hostname);
        }
    } catch (SSLException e) {
        cleanUpFailedSocket(sslSocket);
        throw e;
    } catch (Throwable t) {
        // Make sure we close the socket on any kind of Exception, RuntimeException or Error.
        cleanUpFailedSocket(sslSocket);
        throw new SSLException("Error in hostname verification", t);
    }
}
 
源代码11 项目: j2objc   文件: SSLSocketTest.java
public void test_SSLSocket_SNIHostName() throws Exception {
    TestSSLContext c = TestSSLContext.create();

    final SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket();
    SSLParameters clientParams = client.getSSLParameters();
    clientParams.setServerNames(Collections.singletonList(
            (SNIServerName) new SNIHostName("www.example.com")));
    client.setSSLParameters(clientParams);

    SSLParameters serverParams = c.serverSocket.getSSLParameters();
    serverParams.setSNIMatchers(Collections.singletonList(
            SNIHostName.createSNIMatcher("www\\.example\\.com")));
    c.serverSocket.setSSLParameters(serverParams);

    client.connect(new InetSocketAddress(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 {
            client.startHandshake();
            return null;
        }
    });
    executor.shutdown();
    server.startHandshake();

    SSLSession serverSession = server.getSession();
    assertTrue(serverSession instanceof ExtendedSSLSession);
    ExtendedSSLSession extendedServerSession = (ExtendedSSLSession) serverSession;
    List<SNIServerName> requestedNames = extendedServerSession.getRequestedServerNames();
    assertNotNull(requestedNames);
    assertEquals(1, requestedNames.size());
    SNIServerName serverName = requestedNames.get(0);
    assertEquals(StandardConstants.SNI_HOST_NAME, serverName.getType());
    assertTrue(serverName instanceof SNIHostName);
    SNIHostName serverHostName = (SNIHostName) serverName;
    assertEquals("www.example.com", serverHostName.getAsciiName());
}
 
源代码12 项目: consulo   文件: ConfirmingHostnameVerifier.java
@Override
public 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:
    final InputStream in = ssl.getInputStream();
    in.available();
    // 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);
}
 
源代码13 项目: Pix-Art-Messenger   文件: SSLSocketHelper.java
public static void log(Account account, SSLSocket socket) {
    SSLSession session = socket.getSession();
    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": protocol=" + session.getProtocol() + " cipher=" + session.getCipherSuite());
}
 
源代码14 项目: steady   文件: J_AbstractVerifier_F.java
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);
}
 
源代码15 项目: tomcatsrc   文件: JSSESupport.java
JSSESupport(SSLSocket sock){
    ssl=sock;
    session = sock.getSession();
    sock.addHandshakeCompletedListener(listener);
}
 
源代码16 项目: steady   文件: AbstractVerifierDef.java
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);
}
 
源代码17 项目: Tomcat7.0.67   文件: JSSESupport.java
JSSESupport(SSLSocket sock){
    ssl=sock;
    session = sock.getSession();
    sock.addHandshakeCompletedListener(listener);
}
 
源代码18 项目: openjdk-jdk9   文件: SSLSessionFinalizeTest.java
SBListener doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();

        try {
                SSLSocket sslSocket = (SSLSocket)
                    sslsf.createSocket("localhost", serverPort);
                InputStream sslIS = sslSocket.getInputStream();
                OutputStream sslOS = sslSocket.getOutputStream();

            sslOS.write(280);
            sslOS.flush();
            sslIS.read();

            sslOS.close();
            sslIS.close();

            SSLSession sslSession = sslSocket.getSession();
            System.out.printf(" sslSession: %s %n   %s%n", sslSession, sslSession.getClass());
            SBListener sbListener = new SBListener(sslSession);

            sslSession.putValue("x", sbListener);

            sslSession.invalidate();

            sslSocket.close();

            sslOS = null;
            sslIS = null;
            sslSession = null;
            sslSocket = null;
            Reference.reachabilityFence(sslOS);
            Reference.reachabilityFence(sslIS);
            Reference.reachabilityFence(sslSession);
            Reference.reachabilityFence(sslSocket);

            return sbListener;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw ex;
        }
    }
 
源代码19 项目: YCWebView   文件: WebTlsSniSocketFactory.java
@Override
public Socket createSocket(Socket plainSocket, String host, int port, boolean autoClose)
        throws IOException {
    String peerHost = this.conn.getRequestProperty("Host");
    if (peerHost == null){
        peerHost = host;
    }
    X5LogUtils.i("customized createSocket. host: " + peerHost);
    InetAddress address = plainSocket.getInetAddress();
    if (autoClose) {
        // we don't need the plainSocket
        plainSocket.close();
    }
    // create and connect SSL socket, but don't do hostname/certificate verification yet
    SSLCertificateSocketFactory sslSocketFactory = (SSLCertificateSocketFactory)
            SSLCertificateSocketFactory.getDefault(0);
    SSLSocket ssl = (SSLSocket) sslSocketFactory.createSocket(address, port);

    // enable TLSv1.1/1.2 if available
    ssl.setEnabledProtocols(ssl.getSupportedProtocols());

    // set up SNI before the handshake
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        X5LogUtils.i("Setting SNI hostname");
        sslSocketFactory.setHostname(ssl, peerHost);
    } else {
        X5LogUtils.d("No documented SNI support on Android <4.2, trying with reflection");
        try {
            java.lang.reflect.Method setHostnameMethod =
                    ssl.getClass().getMethod("setHostname", String.class);
            setHostnameMethod.invoke(ssl, peerHost);
        } catch (Exception e) {
            X5LogUtils.e("SNI not useable", e);
        }
    }
    // verify hostname and certificate
    SSLSession session = ssl.getSession();
    if (!hostnameVerifier.verify(peerHost, session)){
        throw new SSLPeerUnverifiedException("Cannot verify hostname: " + peerHost);
    }
    X5LogUtils.i("Established " + session.getProtocol() + " connection with " +
            session.getPeerHost() + " using " + session.getCipherSuite());
    return ssl;
}
 
源代码20 项目: j2objc   文件: RecordedRequest.java
public RecordedRequest(String requestLine, List<String> headers, List<Integer> chunkSizes,
        int bodySize, byte[] body, int sequenceNumber, Socket socket) {
    this.requestLine = requestLine;
    this.headers = headers;
    this.chunkSizes = chunkSizes;
    this.bodySize = bodySize;
    this.body = body;
    this.sequenceNumber = sequenceNumber;

    if (socket instanceof SSLSocket) {
        SSLSocket sslSocket = (SSLSocket) socket;
        SSLSession session = sslSocket.getSession();
        sslProtocol = session.getProtocol();
        sslCipherSuite = session.getCipherSuite();
        sslLocalPrincipal = session.getLocalPrincipal();
        sslLocalCertificates = session.getLocalCertificates();
        Principal peerPrincipal = null;
        Certificate[] peerCertificates = null;
        try {
            peerPrincipal = session.getPeerPrincipal();
            peerCertificates = session.getPeerCertificates();
        } catch (SSLPeerUnverifiedException e) {
            // No-op: use nulls instead
        }
        sslPeerPrincipal = peerPrincipal;
        sslPeerCertificates = peerCertificates;
    } else {
        sslProtocol = null;
        sslCipherSuite = null;
        sslLocalPrincipal = null;
        sslLocalCertificates = null;
        sslPeerPrincipal = null;
        sslPeerCertificates = null;
    }

    if (requestLine != null) {
        int methodEnd = requestLine.indexOf(' ');
        int pathEnd = requestLine.indexOf(' ', methodEnd + 1);
        this.method = requestLine.substring(0, methodEnd);
        this.path = requestLine.substring(methodEnd + 1, pathEnd);
    } else {
        this.method = null;
        this.path = null;
    }
}