當前位置: 首頁>>代碼示例>>Java>>正文


Java SSLSocket類代碼示例

本文整理匯總了Java中javax.net.ssl.SSLSocket的典型用法代碼示例。如果您正苦於以下問題:Java SSLSocket類的具體用法?Java SSLSocket怎麽用?Java SSLSocket使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


SSLSocket類屬於javax.net.ssl包,在下文中一共展示了SSLSocket類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: setUp

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
@Before
public void setUp() throws Exception {
    DummySocket dummySocket = new DummySocket();
    socket = spy(dummySocket);
    socketFactory = mock(SocketFactory.class);
    when(socketFactory.createSocket()).thenReturn(socket);

    sslSocket = mock(SSLSocket.class);
    when(sslSocket.getInputStream()).thenReturn(dummySocket.getInputStream());
    when(sslSocket.getOutputStream()).thenReturn(dummySocket.getOutputStream());

    sslSocketFactory = mock(SSLSocketFactory.class);
    when(sslSocketFactory.createSocket(any(Socket.class), anyString(), anyInt(), anyBoolean()))
            .thenReturn(sslSocket);

    hostnameVerifier = mock(HostnameVerifier.class);
    when(hostnameVerifier.verify(anyString(), any(SSLSession.class))).thenReturn(true);
}
 
開發者ID:pCloud,項目名稱:pcloud-networking-java,代碼行數:19,代碼來源:RealConnectionTest.java

示例2: main

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
public static void main(String[] args) throws Exception {
    try (Server server = new Server()) {
        new Thread(server).start();

        SocketFactory factory = SSLSocketFactory.getDefault();
        try (SSLSocket socket = (SSLSocket) factory.createSocket("localhost",
                server.getPort())) {
            socket.setSoTimeout(2000);
            System.out.println("Client established TCP connection");
            boolean failed = false;
            for (TestCase testCase : testCases) {
                try {
                    testCase.test(socket);
                    System.out.println("ERROR: no exception");
                    failed = true;
                } catch (IOException e) {
                    System.out.println("Failed as expected: " + e);
                }
            }
            if (failed) {
                throw new Exception("One or more tests failed");
            }
        }
    }
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:26,代碼來源:CloseSocket.java

示例3: 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()));
}
 
開發者ID:philipwhiuk,項目名稱:q-mail,代碼行數:22,代碼來源:MockSmtpServer.java

示例4: runClientApplication

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
@Override
protected void runClientApplication(SSLSocket socket) throws Exception {
    String ciphers[] = {
            "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
            "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
            "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
            "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"};
    socket.setEnabledCipherSuites(ciphers);
    socket.setUseClientMode(true);

    InputStream sslIS = socket.getInputStream();
    OutputStream sslOS = socket.getOutputStream();

    sslOS.write(280);
    sslOS.flush();
    sslIS.read();
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:18,代碼來源:UseStrongDHSizes.java

示例5: connectSocket

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
@Override
public Socket connectSocket(
        final int connectTimeout,
        final Socket socket,
        final HttpHost host,
        final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress,
        final HttpContext context) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("Connecting to {}:{}", remoteAddress.getAddress(), remoteAddress.getPort());
    }

    Socket connectedSocket = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);

    if (connectedSocket instanceof SSLSocket) {
        return new SdkSslSocket((SSLSocket) connectedSocket);
    }

    return new SdkSocket(connectedSocket);
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:21,代碼來源:SdkTlsSocketFactory.java

示例6: doServerSide

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket =
        (SSLServerSocket) sslssf.createServerSocket(serverPort);

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write('A');
    sslOS.flush();

    sslSocket.close();
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:24,代碼來源:GenericBlockCipher.java

示例7: handshakeCompleted

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
public void handshakeCompleted(HandshakeCompletedEvent evt) {

        SSLSession session;
        String     sessionId;
        SSLSocket  socket;

        if (Trace.TRACE) {
            socket  = evt.getSocket();
            session = evt.getSession();

            Trace.printSystemOut("SSL handshake completed:");
            Trace.printSystemOut(
                "------------------------------------------------");
            Trace.printSystemOut("socket:      : " + socket);
            Trace.printSystemOut("cipher suite : "
                                 + session.getCipherSuite());

            sessionId = StringConverter.byteToHex(session.getId());

            Trace.printSystemOut("session id   : " + sessionId);
            Trace.printSystemOut(
                "------------------------------------------------");
        }
    }
 
開發者ID:parabuild-ci,項目名稱:parabuild-ci,代碼行數:25,代碼來源:HsqlSocketFactorySecure.java

示例8: supportedSpec

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
/**
 * Returns a copy of this that omits cipher suites and TLS versions not enabled by {@code
 * sslSocket}.
 */
private ConnectionSpec supportedSpec(SSLSocket sslSocket, boolean isFallback) {
  String[] cipherSuitesIntersection = cipherSuites != null
      ? intersect(CipherSuite.ORDER_BY_NAME, sslSocket.getEnabledCipherSuites(), cipherSuites)
      : sslSocket.getEnabledCipherSuites();
  String[] tlsVersionsIntersection = tlsVersions != null
      ? intersect(Util.NATURAL_ORDER, sslSocket.getEnabledProtocols(), tlsVersions)
      : sslSocket.getEnabledProtocols();

  // In accordance with https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00
  // the SCSV cipher is added to signal that a protocol fallback has taken place.
  String[] supportedCipherSuites = sslSocket.getSupportedCipherSuites();
  int indexOfFallbackScsv = indexOf(
      CipherSuite.ORDER_BY_NAME, supportedCipherSuites, "TLS_FALLBACK_SCSV");
  if (isFallback && indexOfFallbackScsv != -1) {
    cipherSuitesIntersection = concat(
        cipherSuitesIntersection, supportedCipherSuites[indexOfFallbackScsv]);
  }

  return new Builder(this)
      .cipherSuites(cipherSuitesIntersection)
      .tlsVersions(tlsVersionsIntersection)
      .build();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:28,代碼來源:ConnectionSpec.java

示例9: isCompatible

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
/**
 * Returns {@code true} if the socket, as currently configured, supports this connection spec. In
 * order for a socket to be compatible the enabled cipher suites and protocols must intersect.
 *
 * <p>For cipher suites, at least one of the {@link #cipherSuites() required cipher suites} must
 * match the socket's enabled cipher suites. If there are no required cipher suites the socket
 * must have at least one cipher suite enabled.
 *
 * <p>For protocols, at least one of the {@link #tlsVersions() required protocols} must match the
 * socket's enabled protocols.
 */
public boolean isCompatible(SSLSocket socket) {
  if (!tls) {
    return false;
  }

  if (tlsVersions != null && !nonEmptyIntersection(
      Util.NATURAL_ORDER, tlsVersions, socket.getEnabledProtocols())) {
    return false;
  }

  if (cipherSuites != null && !nonEmptyIntersection(
      CipherSuite.ORDER_BY_NAME, cipherSuites, socket.getEnabledCipherSuites())) {
    return false;
  }

  return true;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:29,代碼來源:ConnectionSpec.java

示例10: check_nickname

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
public boolean check_nickname(String nickname) throws ClassNotFoundException
{
    //connect to Registrar to check if nickname is unique
    boolean check = false;
    try 
    {
        
        SSLSocket sslSocket=Client.get_SSLSock();
        //Socket s1 = new Socket("localhost", 5999);
        ObjectOutputStream out = new ObjectOutputStream(sslSocket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(sslSocket.getInputStream());

        out.writeObject(new Message(nickname, "null"));//here goes nickname
        out.flush();
        
        check = (boolean)in.readObject();

        sslSocket.close();
    } catch (IOException ex) {
        Logger.getLogger(NewConnection.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    return check;
}
 
開發者ID:georgemakrakis,項目名稱:TrackMeIfYouCanChat,代碼行數:25,代碼來源:Nickname.java

示例11: 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;
}
 
開發者ID:ARMmbed,項目名稱:java-coap,代碼行數:17,代碼來源:SSLSocketClientTransport.java

示例12: extractPeerDNFromSSLSocket

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
/**
 * Returns the DN extracted from the peer certificate (the server DN if run on the client; the client DN (if available) if run on the server).
 *
 * If the client auth setting is WANT or NONE and a client certificate is not present, this method will return {@code null}.
 * If the client auth is NEED, it will throw a {@link CertificateException}.
 *
 * @param socket the SSL Socket
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
public static String extractPeerDNFromSSLSocket(Socket socket) throws CertificateException {
    String dn = null;
    if (socket instanceof SSLSocket) {
        final SSLSocket sslSocket = (SSLSocket) socket;

        boolean clientMode = sslSocket.getUseClientMode();
        logger.debug("SSL Socket in {} mode", clientMode ? "client" : "server");
        ClientAuth clientAuth = getClientAuthStatus(sslSocket);
        logger.debug("SSL Socket client auth status: {}", clientAuth);

        if (clientMode) {
            logger.debug("This socket is in client mode, so attempting to extract certificate from remote 'server' socket");
           dn = extractPeerDNFromServerSSLSocket(sslSocket);
        } else {
            logger.debug("This socket is in server mode, so attempting to extract certificate from remote 'client' socket");
           dn = extractPeerDNFromClientSSLSocket(sslSocket);
        }
    }

    return dn;
}
 
開發者ID:apache,項目名稱:nifi-registry,代碼行數:32,代碼來源:CertificateUtils.java

示例13: handshakeCompleted

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
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(
                "------------------------------------------------");
        }
    }
 
開發者ID:tiweGH,項目名稱:OpenDiabetes,代碼行數:24,代碼來源:HsqlSocketFactorySecure.java

示例14: Entry

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
public Entry(URI uri, RawHeaders varyHeaders, HttpURLConnection httpConnection)
    throws IOException {
  this.uri = uri.toString();
  this.varyHeaders = varyHeaders;
  this.requestMethod = httpConnection.getRequestMethod();
  this.responseHeaders = RawHeaders.fromMultimap(httpConnection.getHeaderFields(), true);

  SSLSocket sslSocket = getSslSocket(httpConnection);
  if (sslSocket != null) {
    cipherSuite = sslSocket.getSession().getCipherSuite();
    Certificate[] peerCertificatesNonFinal = null;
    try {
      peerCertificatesNonFinal = sslSocket.getSession().getPeerCertificates();
    } catch (SSLPeerUnverifiedException ignored) {
    }
    peerCertificates = peerCertificatesNonFinal;
    localCertificates = sslSocket.getSession().getLocalCertificates();
  } else {
    cipherSuite = null;
    peerCertificates = null;
    localCertificates = null;
  }
}
 
開發者ID:aabognah,項目名稱:LoRaWAN-Smart-Parking,代碼行數:24,代碼來源:HttpResponseCache.java

示例15: supportedSpec

import javax.net.ssl.SSLSocket; //導入依賴的package包/類
private ConnectionSpec supportedSpec(SSLSocket sslSocket, boolean isFallback) {
    String[] cipherSuitesIntersection;
    String[] tlsVersionsIntersection;
    if (this.cipherSuites != null) {
        cipherSuitesIntersection = (String[]) Util.intersect(String.class, this.cipherSuites,
                sslSocket.getEnabledCipherSuites());
    } else {
        cipherSuitesIntersection = sslSocket.getEnabledCipherSuites();
    }
    if (this.tlsVersions != null) {
        tlsVersionsIntersection = (String[]) Util.intersect(String.class, this.tlsVersions,
                sslSocket.getEnabledProtocols());
    } else {
        tlsVersionsIntersection = sslSocket.getEnabledProtocols();
    }
    if (isFallback && Util.contains(sslSocket.getSupportedCipherSuites(),
            "TLS_FALLBACK_SCSV")) {
        cipherSuitesIntersection = Util.concat(cipherSuitesIntersection, "TLS_FALLBACK_SCSV");
    }
    return new Builder(this).cipherSuites(cipherSuitesIntersection).tlsVersions
            (tlsVersionsIntersection).build();
}
 
開發者ID:JackChan1999,項目名稱:boohee_v5.6,代碼行數:23,代碼來源:ConnectionSpec.java


注:本文中的javax.net.ssl.SSLSocket類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。